yxc-dfs
class Solution {
public:
vector<vector<int>> ans;
vector<int> res;
int size=0;
vector<vector<int>> permutation(vector<int>& nums) {
size=nums.size();
res.resize(size);
sort(nums.begin(), nums.end());
dfs(nums, 0, 0, 0);
return ans;
}
void dfs(vector<int> &nums, int u, int start, int st)
{
if(u==size)
{
ans.emplace_back(res);
return;
}
if(!u||nums[u]!=nums[u-1]) start = 0;
for(int i=start; i<size; ++i)
if(!(st>>i&1))
{
res[i] = nums[u];
dfs(nums, u+1, i+1, st+(1<<i));
}
}
};
next_permutation
class Solution {
public:
vector<vector<int>> permutation(vector<int>& nums) {
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
do{
ans.emplace_back(nums);
}while(next_permutation(nums.begin(), nums.end()));
return ans;
}
};
递归(可能超时),AcWing.823题写的,不是乐扣形式
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int s[10];
vector<vector<int>> ans;
vector<int> res;
void perm(int a[], int l, int r)
{
if(r==l)
{
for(int i=1;i<=r;++i) res.emplace_back(a[i]);
ans.emplace_back(res);
res.clear();
}else
{
for(int i=l;i<=r;++i)
{
swap(a[l], a[i]);
perm(a, l+1, r);
swap(a[l], a[i]);
}
}
}
int main()
{
int n;
scanf("%d", &n);
for(int i=0;i<=n;++i) s[i]=i;
perm(s,1,n);
sort(ans.begin(), ans.end());
for(int i=0; i<ans.size(); ++i)
{
for(int j=0; j<n; ++j)
{
printf("%d ", ans[i][j]);
}
puts("");
}
return 0;
}