解:
先举个例子看看:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
三位数时有6种情况,以位数划分,从高位向低位,可总结出,百位有3种情况(1,2,3),在百位确定的情况下,十位有2种情况,而个位固定。共3x2情况。
再看四位数,最高位有4种情况,然后就与三位数情况相同,共4x3x2种。
因此可以用位数当参数来确定递归次数。这个参数也可以用来确定当前位数有几种情况。
当参数为1时,就可以输出数组,并
r
e
t
u
r
n
return
return。
需要注意的是数组属于引用类型,作为参数传递时,指向的是同一片地址,数的交换方式就要变化下。
多次尝试后,得出方便计算的排序,如下:
1 2 3
1 3 2
3 1 2
3 2 1
2 3 1
2 1 3
用
w
h
i
l
e
while
while 交换数的从当前值到右边一位就好。
只能执行三位数的全排列,四位数还有bug。
代码:
#include <iostream>
using namespace std;
const int lenth=4;//计算的全排列的长度
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
/*
void all(int a,int b,int c,bool flag){
cout<<a<<b<<c<<endl;
cout<<a<<c<<b<<endl;
if(flag==true)return;
flag=true;
all(b,a,c,flag);
all(c,a,b,flag);
}
*/
void alll(int a,int num[]){
int time=a-1;//可以不用减一,不减一方便很多
int temp;
if(time==0){
for(int i=0;i<lenth;i++)
cout<<num[i];
cout<<endl;
return;
}
while(a){//a表示几种情况
int l=lenth-time-1,r=lenth-a;
if(r-l>1)r=l+1;
if(l!=r){
temp=num[l];
num[l]=num[r];
num[r]=temp;
}
alll(time,num);
a--;
}
}
int main(int argc, char *argv[]) {
/*
int a,b,c;
cin>>a>>b>>c;
all(a,b,c,false);
*/
int num[lenth];
for(int i=0;i<lenth;i++){
cin>>num[i];
}
alll(lenth,num);
return 0;
}