题目:
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]
.
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> res; if(nums.empty()) return res; permute(nums,0,res); return res; } void permute(vector<int>& nums,int index, vector<vector<int>> &res) { if(index==nums.size()) { res.push_back(nums); return; } permute(nums,index+1,res); unordered_set<int> prev;//用哈希表记录。避免反复值 prev.emplace(nums[index]); for(int i=index+1;i<nums.size();++i) { if(prev.count(nums[i])>0)//忽略反复值 continue; prev.emplace(nums[i]); swap(nums[index],nums[i]); permute(nums,index+1,res); swap(nums[index],nums[i]); } } };