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]
]
思路:
void permuteUniqueCore(vector<vector<int>>& result, vector<int> nums, int index) { if (index == nums.size()) { result.push_back(nums); } for (int i = index; i < nums.size(); i++) { if (i!=index && nums[i]==nums[index])continue;// swap(nums[i], nums[index]); permuteUniqueCore(result, nums, index + 1); //swap(nums[i], nums[index]); //不要交换。。。了。。 参数nums 也是变成了传值 不是传引用 } } vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>>result; sort(nums.begin(), nums.end()); permuteUniqueCore(result, nums, 0); return result; }
参考: