[LeetCode] 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], [2,1,1] ]
给定一个包含重复元素的数组,找出其所有全排列中不重复的那些组合。
思路:使用backtracking算法。
helper函数用于寻找下一个元素,swap用于构造全排列。
class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> res; int idx = 0; helper(res, nums, idx); return res; } void helper(vector<vector<int>>& res, vector<int>& nums, int idx) { if (idx >= nums.size()) { if (find(res.begin(), res.end(), nums) == res.end()) { res.push_back(nums); } } else { for (int i = idx; i < nums.size(); i++) { swap(nums[i], nums[idx]); helper(res, nums, idx + 1); swap(nums[i], nums[idx]); } } } }; // 469 ms