基本思路就是:
1、判断是否到达数组末尾,若是,输出数组,返回。
2、否则依次取出片段数组的每个元素,对剩下的元素组成的片段数组再进行排列。
注意,生成第二步的剩余片段数组的技巧是将每个元素与片段首个元素互换,这样首个元素之后到数组末尾的连续元素 就是 剩余片段数组——当然,互换完了还要互换回来,否则 第二步的剩余片段数组 的内容就会混乱。
- #include<stdio.h>
- #include<stdlib.h>
- voidswapArrayElements(chara[],intlhs,intrhs)
- {
- chartemp;
- temp=a[lhs];
- a[lhs]=a[rhs];
- a[rhs]=temp;
- }
- voidperm(chara[],intstart,intend)
- {
- inti,j;
- if(start==end){
- //输出排列结果
- for(j=0;j<=end;j++)
- putchar(a[j]);
- putchar('/n');
- return;
- }else{
- for(i=start;i<=end;i++){
- //将数组片段的各元素与首元素交换
- swapArrayElements(a,start,i);
- //对交换后的,去掉首元素的数组片段进行全排列
- perm(a,start+1,end);
- //交换回来
- swapArrayElements(a,start,i);
- }
- }
- }
- main()
- {
- chara[]={'A','B','C','D'};
- perm(a,0,3);
- system("pause");
- }
基本思路就是:
1、判断是否到达数组末尾,若是,输出数组,返回。
2、否则依次取出片段数组的每个元素,对剩下的元素组成的片段数组再进行排列。
注意,生成第二步的剩余片段数组的技巧是将每个元素与片段首个元素互换,这样首个元素之后到数组末尾的连续元素 就是 剩余片段数组——当然,互换完了还要互换回来,否则 第二步的剩余片段数组 的内容就会混乱。
- #include<stdio.h>
- #include<stdlib.h>
- voidswapArrayElements(chara[],intlhs,intrhs)
- {
- chartemp;
- temp=a[lhs];
- a[lhs]=a[rhs];
- a[rhs]=temp;
- }
- voidperm(chara[],intstart,intend)
- {
- inti,j;
- if(start==end){
- //输出排列结果
- for(j=0;j<=end;j++)
- putchar(a[j]);
- putchar('/n');
- return;
- }else{
- for(i=start;i<=end;i++){
- //将数组片段的各元素与首元素交换
- swapArrayElements(a,start,i);
- //对交换后的,去掉首元素的数组片段进行全排列
- perm(a,start+1,end);
- //交换回来
- swapArrayElements(a,start,i);
- }
- }
- }
- main()
- {
- chara[]={'A','B','C','D'};
- perm(a,0,3);
- system("pause");
- }