Permutations II 字符全排列 去除重复的
原创
©著作权归作者所有:来自51CTO博客作者我想有个名字的原创作品,请联系作者获取转载授权,否则将追究法律责任
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());
}
};