和组合数枚举不同的是不需要剪枝,因为数值及其个数已经给定,而且用过的数会用chosen锁住,回溯的时候再解锁并将数值归零。注意这里的order数组和chosen数组的值,order的索引是x的值,chosen数组的索引是循环的i变量。这里也可以创建数组存值调用求排列情况。
#include<bits/stdc++.h>
using namespace std;int n;
bool chosen[20];//0 1
int order[20];//存储具体的数值 void calc(int x)
{//这里不需要单独剪枝,因为已经给了具体的数值和个数 //条件检查 if(x-1==n){for(int i=1;i<=n;i++){cout<<order[i];}puts(" ");return;}//递归 for(int i=1;i<=n;i++){if(chosen[i])//这里相当于剪枝了 ,用过的数没解放,不能用了 continue; order[x]=i;//存值 chosen[i]=1; //锁 calc(x+1);order[x]=0;//归零 chosen[i]=0; //解锁 }
}int main()
{cin>>n;calc(1);return 0;}