这题倒也花了我不少时间,不停想节省空间,但这也确实是最省的了。。。
主要思路呢,要注意标记数有没有选过,并标记每个数的输出顺序。。
具体注释见代码:
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 int n;//输入的数 5 int a[15],b[15];//第一个用来标记数有没有选过,第二个标记输出数的顺序 6 void sc(){//输出函数 7 for(int i=1;i<=n;i++) 8 printf("%5d",b[i]);//注意题目要求“每个数字保留5个常宽” 9 cout<<endl;//换行 10 } 11 void dfs(int l){ 12 if(l>n){//判断停止条件 13 sc();//调用函数 14 return;//返回 15 } 16 for(int i=1;i<=n;i++){//循环 17 if(!a[i]){//如果数没有被选过 18 a[i]=l;//数被选过了 19 b[l]=i;//数是第几个被选的,也就是输出顺序 20 dfs(l+1);//回溯 21 b[l]=0; 22 a[i]=0; 23 } 24 } 25 } 26 int main(){ 27 cin>>n;//输入 28 dfs(1);//调用函数 29 return 0; 30 }
新人开博鼓励一下嘛~~~