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]
]
C++
//backtrack
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
if(nums.size() == 0) return res;
//排序,方便剪枝
sort(nums.begin(), nums.end());
vector<int> path;
vector<bool> used(10000,0);
backtrack(res ,path, used, nums, 0);
return res;
}
void backtrack(vector<vector<int>>& res, vector<int> path, vector<bool> used, vector<int> nums, int depth){
if(depth == nums.size()){
res.push_back(path);
return;
}
for(int i = 0; i < nums.size(); i++){
if(used[i]){
continue;
}
//剪枝, i > 0 保证 nums[i - 1]有意义
//used[i - 1] 是因为 nums[i - 1] 在回退的过程中刚刚被撤销选择
if( i > 0 && nums[i] == nums[i - 1] && used[i - 1 ] == false){
continue;
}
path.push_back(nums[i]);
used[i] = true;
backtrack(res, path, used, nums, depth + 1);
path.pop_back();
used[i] = false;
}
}
};