Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
思路
1 class Solution { 2 public: 3 vector<vector<int>> permuteUnique(vector<int>& nums) { 4 int len = nums.size(); 5 sort(nums.begin(), nums.end()); 6 vector<int> v; 7 vector<vector<int> > res; 8 vector<bool> visited(len, false); 9 permuteUnique(nums, v, res, visited, 0, len); 10 return res; 11 } 12 //visited用于判断是否访问过, i表示v的长度, len表示nums的长度 13 void permuteUnique(vector<int> &nums, vector<int> &v, vector<vector<int> > &res, vector<bool> &visited, int i, int len) { 14 if (i == len) { 15 res.push_back(v); 16 return ; 17 } 18 for (int k = 0; k < len; k++) { 19 if (k > 0 && nums[k] == nums[k - 1] && visited[k - 1]) { 20 continue; 21 } 22 if (visited[k] == false) { 23 visited[k] = true; 24 v.push_back(nums[k]); 25 permuteUnique(nums, v, res, visited, i + 1, len); 26 v.pop_back(); 27 visited[k] = false; 28 } 29 } 30 } 31 32 };