题目描述:
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]
.
解题思路:
思路和上题目相似,但需要跳过重复的元素
1 class Solution { 2 public: 3 vector<vector<int>> permuteUnique(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 vector<vector<int>> result; 6 vector<int> elem; 7 vector<bool> visited(nums.size(), false); 8 permute(nums, visited, result, elem); 9 return result; 10 } 11 private: 12 void permute(const vector<int> &nums, vector<bool> &visited, vector<vector<int>> &result, vector<int> &elem) { 13 if (nums.size() == elem.size()) { 14 result.push_back(elem); 15 return; 16 } 17 18 for (int i = 0; i < nums.size(); ++i) { 19 if (!visited[i]) { 20 visited[i] = true; 21 elem.push_back(nums[i]); 22 permute(nums, visited, result, elem); 23 elem.pop_back(); 24 visited[i] = false; 25 while (i < nums.size() - 1 && nums[i] == nums[i + 1]) ++i; // 跳过重复的元素 26 } 27 } 28 } 29 };