AcWing 823. 排列
原题链接
简单
作者:
桻
,
2024-11-21 21:07:34
,
所有人可见
,
阅读 1
dfs
#include <iostream>
using namespace std;
const int N = 10;//一共有0-9个数
int n;
void dfs(int u,int nums[],bool st[])//u代表层数
{
if(u > n)//枚举到最后一层
{
for (int i = 0; i <= n;i ++)
cout << nums[i] << ' ';
cout << endl;
}
else
{
for (int i = 1; i <= n;i ++)//按照字典序遍历数字
{
if(!st[i])
{
st[i] = true;//标记已经存了数字
nums[u] = i;//存入数字
dfs(u + 1, nums, st);//进入下一层
st[i] = false;//恢复现场
}
}
}
}
int main()
{
cin >> n;
int nums[N];
bool st[N] = {0};
dfs(1, nums, st);
}
next_permutation函数
#include<bits/stdc++.h>
using namespace std;
const int N = 10;
int a[N];
int n;
int main()
{
cin >> n;
for (int i = 0; i < n; i ++)
a[i] = i + 1;
for (int i = 0; i < n; i++)
cout << a[i] << ' ';
cout << endl;
while(next_permutation(a,a+n))
{
for (int i = 0; i < n; i++)
cout << a[i] << ' ';
cout << endl;
}
}