这个题目和上一个题目差不多,但是不能出现重复项 其实很简单,先把原数组排序,然后(i>0&&nums[i]==nums[i-1]&&visited[i-1]==0) 跳过
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
int len=nums.size();
int begin=0;
vector<int> visited(len,0);
vector<int> path;
vector<vector<int>> res;
if(len==0){
return res;
}
sort(nums.begin(),nums.end());
dfs(nums,len,visited,begin,path,res);
return res;
}
void dfs(vector<int>& nums,int len,vector<int> visited,int begin,vector<int> path,vector<vector<int>>& res){
if(begin==len){
res.push_back(path);
return;
}
for(int i=0;i<len;i++){
if(visited[i]!=0||(i>0&&nums[i]==nums[i-1]&&visited[i-1]==0)){
continue;
}
path.push_back(nums[i]);
visited[i]=1;
dfs(nums,len,visited,begin+1,path,res);
path.pop_back();
visited[i]=0;
}
}
};
|