AcWing 842. 全排列(开挂写法)
原题链接
简单
作者:
Anohkx
,
2023-08-08 21:31:40
,
所有人可见
,
阅读 319
1.开挂写法
#include <bits/stdc++.h>
using namespace std;
int n;
int a[20];
int main()
{
cin >> n;
for(int i = 1; i <= n; ++ i)
a[i] = i;
do
{
for(int i = 1; i <= n; ++ i)
cout << a[i] << ' ';
cout << endl;
}while(next_permutation(a + 1, a + n + 1));//牢记用法
}
2.正常写法dfs
#include <bits/stdc++.h>
using namespace std;
int n;
int a[20];
bool is_used[20];
void dfs(int x)
{
if(x == n + 1)//这里注意+1
{
for(int i = 1; i <= n; ++ i)
cout << a[i] << ' ';
cout << endl;
}
for(int i = 1; i <= n; ++ i)
{
if(!is_used[i])
{
is_used[i] = 1;
a[x] = i;
dfs(x + 1);
is_used[i] = 0;
}
}
}
int main()
{
cin >> n;
dfs(1);
}
有点厉害,学到了