这个题按照书上的解法,输出顺序并不是字典序,所以在网上找到了一个很棒的解法,先写到这里记录下来。
#include
using namespace std;
int a[100];
void dfs(int cur,int n)//cur表示目前正在填的数,n表示总共要填的数
{
if(cur==n)//递归边界,说明填完了
{
for(int i=0;i
cout<
cout<
}
for(int i=1;i<=n;i++)//把数字1-n填入
{
int ok=1;
for(int j=0;j
{
if(a[j]==i) ok=0;
}
if(ok==1)
{
a[cur]=i;//没有填过就填 ,把它放在a数组的最后
dfs(cur+1,n);//再排A数组元素里面的第cur+1个位置 (这里就不需要设置撤销的动作了~反正每次进来都会判断数字有没有填过)
}
}
}
int main()
{
int n;
cin>>n;
dfs(0,n);
return 0;
}
以上是找到的解法,我自己写的是下面的,但是不能够按照字典顺序输出
#include
using namespacestd;
templateinlinevoid Swap(type & a, type &b)
{
type temp=a;
a=b;
b=temp;
}
template
void Perm(type list[],int k, intm)
{if(m ==k)
{for(int i = 0;i <= m;i++)
cout<
cout<
}else{for(int i = k;i <= m;i++)
{
Swap(list[k], list[i]);
Perm(list, k+1, m);
Swap(list[k], list[i]);
}
}
}intmain()
{int N, num[10];
cin>>N;for(int i = 1, j = 0;i <= N;i++, j++)
{
num[j]=i;
}
Perm(num,0, N-1);return 0;
}