#include using namespace std; const int N=10; bool st[N];//判断当前数字是否被使用过 int path[N];//存放当前方案 int n; void dfs(int u) { if(u==n) { for(int i=0;i<n;i++) cout<<path[i]<<" "; cout<<endl; return; } for(int i=1;i<=n;i++)//枚举每个数字 { if(!st[i])//如果这个数字没有被使用过 { path[u]=i;//选择这个数字 st[i]=true;//将这个数字标记为使用过 dfs(u+1);//继续搜索下一个数字 st[i]=false;//回溯,将这个数字的使用状态恢复 } } } int main() { cin>>n; dfs(0);//从第0个位置开始搜索 return 0;

输出自然数1~n所有不重复的排列即n的全排列要求所产生的任一数字序列中不允许出现重复数字。输入格式 1=n=9输出格式 由1~n组成的所有不重复的数字序列。每行一个序列输入样例3输出样例1 2 31 3 22 1 32 3 13 1 23 2 1深搜算法解决

原文地址: http://www.cveoy.top/t/topic/euXd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录