现在的位置: 首页 > 综合 > 正文

产生所有排列—旋转法——2013年1月22日

2013年12月06日 ⁄ 综合 ⁄ 共 660字 ⁄ 字号 评论关闭

        我觉得这是一个很巧秒的算法。思路非常直接,从代码里可以很容易看出来,再单步调试查看set数组的值就可以很清楚地明白算法的过程。

        代码如下:

复制代码
 1 #include <stdio.h>
 2 #define MAX 1000
 3 
 4 int n=3;  //the number of set element
 5 int set[MAX]={1,2,3};
 6 
 7 //move the set[0] to set[position]
 8 int rotate(int position)
 9 {
10     int temp=set[0]; 
11     int index;
12     for(index=1;index<=position;index++)
13         set[index-1]=set[index];
14     set[position]=temp;
15 }
16 
17 void set_print()
18 {
19     int index;
20     for(index=0;index<n;index++)
21         printf("%d ",set[index]);
22     printf("\n");
23 }
24 int main()
25 {
26     int position=n-1;
27     while(position!=0)  
28     {
29         position=n-1; 
30         rotate(position);
31         set_print();
32         while(set[position]==position+1 && position!=0)
33         {
34             position--; 
35             rotate(position);
36         }
37     }
38 }
复制代码

        参考资料:《C语言名题精选百则技巧篇》

抱歉!评论已关闭.