求全排列问题

基本思路就是:
1、判断是否到达数组末尾,若是,输出数组,返回。
2、否则依次取出片段数组的每个元素,对剩下的元素组成的片段数组再进行排列。

注意,生成第二步的剩余片段数组的技巧是将每个元素与片段首个元素互换,这样首个元素之后到数组末尾的连续元素 就是 剩余片段数组——当然,互换完了还要互换回来,否则 第二步的剩余片段数组 的内容就会混乱。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. voidswapArrayElements(chara[],intlhs,intrhs)
  4. {
  5. chartemp;
  6. temp=a[lhs];
  7. a[lhs]=a[rhs];
  8. a[rhs]=temp;
  9. }
  10. voidperm(chara[],intstart,intend)
  11. {
  12. inti,j;
  13. if(start==end){
  14. //输出排列结果
  15. for(j=0;j<=end;j++)
  16. putchar(a[j]);
  17. putchar('/n');
  18. return;
  19. }else{
  20. for(i=start;i<=end;i++){
  21. //将数组片段的各元素与首元素交换
  22. swapArrayElements(a,start,i);
  23. //对交换后的,去掉首元素的数组片段进行全排列
  24. perm(a,start+1,end);
  25. //交换回来
  26. swapArrayElements(a,start,i);
  27. }
  28. }
  29. }
  30. main()
  31. {
  32. chara[]={'A','B','C','D'};
  33. perm(a,0,3);
  34. system("pause");
  35. }
 
 

基本思路就是:
1、判断是否到达数组末尾,若是,输出数组,返回。
2、否则依次取出片段数组的每个元素,对剩下的元素组成的片段数组再进行排列。

注意,生成第二步的剩余片段数组的技巧是将每个元素与片段首个元素互换,这样首个元素之后到数组末尾的连续元素 就是 剩余片段数组——当然,互换完了还要互换回来,否则 第二步的剩余片段数组 的内容就会混乱。

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. voidswapArrayElements(chara[],intlhs,intrhs)
  4. {
  5. chartemp;
  6. temp=a[lhs];
  7. a[lhs]=a[rhs];
  8. a[rhs]=temp;
  9. }
  10. voidperm(chara[],intstart,intend)
  11. {
  12. inti,j;
  13. if(start==end){
  14. //输出排列结果
  15. for(j=0;j<=end;j++)
  16. putchar(a[j]);
  17. putchar('/n');
  18. return;
  19. }else{
  20. for(i=start;i<=end;i++){
  21. //将数组片段的各元素与首元素交换
  22. swapArrayElements(a,start,i);
  23. //对交换后的,去掉首元素的数组片段进行全排列
  24. perm(a,start+1,end);
  25. //交换回来
  26. swapArrayElements(a,start,i);
  27. }
  28. }
  29. }
  30. main()
  31. {
  32. chara[]={'A','B','C','D'};
  33. perm(a,0,3);
  34. system("pause");
  35. }

猜你喜欢

转载自vergilwang.iteye.com/blog/2011236
今日推荐