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

简介:
       我觉得这是一个很巧秒的算法。思路非常直接,从代码里可以很容易看出来,再单步调试查看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 }
本文转自NeilHappy 51CTO博客,原文链接:http://blog.51cto.com/neilhappy/1124040,如需转载请自行联系原作者
相关文章
|
6月前
数组篇----495
数组篇----495
|
6月前
数组篇----485
数组篇----485
|
机器学习/深度学习 人工智能
排序----4种排序
排序----4种排序
50 0
leetcode------二维数组中的查找
leetcode------二维数组中的查找
51 0
洛谷题单P1007---独木桥
洛谷题单P1007---独木桥
73 0
你知道的----qsort函数排序
目录: 一、 qsort 函数介绍 二、qsort的四个参数解读 三、qsort函数具体例子:
100 0
|
算法
Java----------LeetCode----------46. 全排列
说起回溯算法,渊源颇深,我上次做过一道,本应该这次能拿下但是,又没拿下,不过这次有点理解它的思想了, 每次的回溯就是一个二叉树,简单的说,就是你执行的操作需要回溯时它会返回调用它的方法哪里的状态,进行下一步的执行。
1075 0