Leetcode_46. 全排列_47. 全排列 II
简单搜索
code
class Solution {
public:
bool vis[100005]={false};
void dfs(vector<vector<int>>& ans,vector<int>& a,int idx,vector<int>& nums,int n){
if(idx==n){
ans.push_back(a);
return;
}
for(int i=0;i<n;i++){
if(!vis[i]){
vis[i]=true;
a.push_back(nums[i]);
dfs(ans,a,idx+1,nums,n);
a.pop_back();
vis[i]=false;
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> a;
int n=nums.size();
dfs(ans,a,0,nums,n);
return ans;
}
};
class Solution {
public:
bool vis[100005]={false};
void dfs(set<vector<int>>& ans,vector<int>& a,int idx,vector<int>& nums,int n){
if(idx==n){
ans.insert(a);
return;
}
for(int i=0;i<n;i++){
if(!vis[i]){
vis[i]=true;
a.push_back(nums[i]);
dfs(ans,a,idx+1,nums,n);
a.pop_back();
vis[i]=false;
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
set<vector<int>> ans;
vector<int> a;
int n=nums.size();
dfs(ans,a,0,nums,n);
vector<vector<int>> res;
for(auto s:ans){
res.push_back(s);
}
return res;
}
};