您的位置:首页 > 其它

字符串全排列问题(递归算法)

2017-06-30 08:36 197 查看
#include <stdio.h>
void swap(char array[],int src,int dst)
{
char temp = array[src];
array[src] = array[dst];
array[dst] = temp;
}

void Permutation(char array[],int from , int to )
{
printf("start..from = %d,to = %d \n",from,to);
int i=0;
if(from == to)
{
for(i=0;i<=to;i++)
{
printf("%c",array[i]);
}
printf("\n");
}

for(i=from;i<=to;i++)
{
swap(array,i,from);
Permutation(array,from+1,to);
swap(array,i,from);
}
}

int main()
{
char str[] = "1234";
int len = sizeof(str)/sizeof(char);
Permutation(str,0,len-2);
}






以1234为例:

采用递归的思想:

1 -> 2 3 4 继续调用自身做n-1规模的全排列

2 -> 1 3 4 swap之后,继续调用自身做n-1规模的全排列

3 -> 2 1 4 swap之后,继续调用自身。。。。

4 -> 2 3 1 同上 

注意:每次调用前保证1234的顺序不变,否则会有遗漏
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: