46. 全排列
简单递归
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN=1e6+10;
int a[10],vis[10];
int n;
vector<vector<int>> ans;
void dfs(vector<int> v) {
if (v.size()==n) {
ans.push_back(v);
return ;
}
for (int i=0;i<n;i++) {
if (!vis[i]) {
vis[i]=1;
v.push_back(a[i]);
dfs(v);
v.pop_back();
vis[i]=0;
}
}
}
int main() {
freopen("in.txt","r",stdin);
cin>>n;
for (int i=0;i<n;i++) {
cin>>a[i];
}
dfs({});
for (auto vc: ans) {
for (auto x: vc) {
cout<<x<<" ";
}
cout<<endl;
}
return 0;
}
粘贴到leetcode中
46. 全排列
class Solution {
public:
vector<vector<int>> ans;
int vis[10009];
int n;
vector<vector<int>> permute(vector<int>& nums) {
memset(vis,0,sizeof(vis));
ans.clear();
n=nums.size();
dfs({},nums);
return ans;
}
void dfs(vector<int> v,vector<int>& nums) {
if (v.size()==n) {
ans.push_back(v);
return ;
}
for (int i=0;i<n;i++) {
if (!vis[i]) {
vis[i]=1;
v.push_back(nums[i]);
dfs(v,nums);
v.pop_back();
vis[i]=0;
}
}
}
};