Permutations II



Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,

​[1,1,2]​​ have the following unique permutations:

​[1,1,2]​​, ​​[1,2,1]​​, and ​​[2,1,1]​​.


Hide Tags

 

​Backtracking​


class Solution {
public:
//先排序,以[1, 1, 2],第一个1处理过以后,第二个1就可以跳掉了。
vector<vector<int>> permuteUnique(vector<int>& nums) {

int n=nums.size();
vector< vector<int> >res;
vector< int > path;

sort(nums.begin(),nums.end());
solve(res,nums,path,0,n);

return res;
}

void solve(vector< vector<int> > &res, vector<int> &nums,vector<int> &path, int index, int n)
{
if(index==n)
{
res.push_back(path);
return ;
}

for(int i=index;i<n;i++)
{
if(i>index && nums[i]==nums[index])//相等 不考虑
continue;
else
swap(nums[i],nums[index]);

path.push_back(nums[index]);
solve(res,nums,path,index+1,n);
path.pop_back();
}
sort(nums.begin()+index,nums.end());
}
};