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]
.
class Solution {
public:
/*algorithm: dfs
*/
void dfs(vector<vector<int> >&result,vector<int>&path,vector<int>&nums,vector<int>&visited){
if(path.size()==nums.size()){
result.push_back(path);
return;
}
for(int i = 0;i < nums.size();++i){
if(visited[i])continue;
visited[i] = 1;
path.push_back(nums[i]);
dfs(result,path,nums,visited);
path.pop_back();
visited[i]=0;
while((i+1)<nums.size() && nums[i]==nums[i+1])++i;
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>>result;
vector<int>path,visited(nums.size(),0);
sort(nums.begin(),nums.end());
dfs(result,path,nums,visited);
return result;
}
};