47. Permutations II (Medium)
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]
]
Solution:
class Solution {
void dfs(vector<int> nums, int i, vector<vector<int>>& res) {
if (i == nums.size()-1) {res.push_back(nums); return;}
for (int k = i; k < nums.size(); ++k) {
if (k != i && nums[k] == nums[i]) continue;
swap(nums[i], nums[k]);
dfs(nums, i+1, res);
}
}
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
dfs(nums, 0, res);
return res;
}
};