Files
python/C++专题课程/全排列/全排列_1.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

38 lines
667 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//输入一个数n(1<=n<=9),输出1~n的全排列
#include<bits/stdc++.h>
int book[10];//标记排列中已有的数字
int array[10];//排列
//本次输出多少个数的全排列
int n;
//dfs深度优先搜索
void dfs(int step)
{
if(step==n+1){
for(int i=1;i<=n;i++)
printf("%d%c",array[i],i==n?'\n':' ');
return;
}
for(int i=1;i<=n;i++){
if(book[i]==0){
array[step]=i;
book[i]=1;
dfs(step+1);
book[i]=0;
}
}
return;
}
int main()
{
//初始化book数组
memset(book,0,sizeof(book));
//接收个数
scanf("%d",&n);
dfs(1);
return 0;
}