当日总结
递归实现排列型枚举
法一:
考虑在各个位置上放哪些数字
include
using namespace std;
int n;
const int N=20;
int arr[N];
bool st[N];
void dfs(int x){
if(x>n)
{
for(int i=1;i<=n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return;
}
for(int i=1;i<=n;i++)
{
if(!st[i])
{
// arr[x]=i;
st[i]=true;
arr[x]=i;
dfs(x+1);
arr[x]=0;
st[i]=false;
}
}
}
int main(){
cin>>n;
dfs(1);
return 0;
}
法二:
考虑各个数字放在哪个位置上
include
using namespace std;
int n;
const int N = 20;
int arr[N]; // 存储当前排列,arr[x]表示第x个位置的数字
int st[N]; // 标记数字是否被使用,st[i]=1表示数字i已使用
void dfs(int x) {
if (x > n) { // 递归终止条件:已填满n个位置
for (int i = 1; i <= n; i++) {
cout << arr[i];
}
cout << endl;
return;
}
// 尝试将1~n中未使用的数字放入第x个位置
for (int i = 1; i <= n; i++) {
if (!st[i]) { // 若数字i未被使用
arr[x] = i; // 第x个位置放数字i
st[i] = 1; // 标记数字i已使用
dfs(x + 1); // 递归处理下一个位置
st[i] = 0; // 回溯:释放数字i,允许其他位置使用
}
}
}
int main() {
cin >> n;
dfs(1); // 从第1个位置开始递归
return 0;
}

浙公网安备 33010602011771号