# LeetCode Permutations II

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]
]```

• 1,2,3
• 2,1,3
• 3,2,1

• 2,3
• 3,2

• 1,2,3
• 1,3,2

```class Solution {
public:
void work(set<vector<int>>& ans, vector<int>& nums, int start) {
if (start == nums.size()) {
ans.insert(nums);
}
else {
for (int i = start; i < nums.size(); i++) {
if (i != start&&nums[i] == nums[i - 1])continue;
swap(nums[i], nums[start]);
work(ans, nums, start + 1);
swap(nums[i], nums[start]);
}
}
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
set<vector<int>> ans;
work(ans, nums, 0);
return vector<vector<int>>(ans.begin(),ans.end());
}
};
```

```class Solution {
private:
void dfs(const vector<int>& nums, vector<vector<int>>& ans, vector<int>& cand, vector<int> &visited) {
if (cand.size() == nums.size()) {
ans.push_back(cand);
return;
}
int last = INT_MAX;
for (int i = 0; i < nums.size(); ++i) {
if (visited[i] == 0) {
if (i != 0 && nums[i] == last)continue; // 不能和上一次递归的元素相同，否则产生冗余排列
cand.push_back(nums[i]);
last = nums[i];
visited[i] = 1;
dfs(nums, ans, cand, visited);
visited[i] = 0;
cand.pop_back();
}
}
}

public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
vector<int> cand, visited(nums.size(), 0);
dfs(nums, ans, cand, visited);
return ans;
}
};
```

```class Solution {
private:
void dfs(const vector<int>& nums, vector<vector<int>>& ans, vector<int>& cand, vector<int> &visited) {
if (cand.size() == nums.size()) {
ans.push_back(cand);
return;
}
for (int i = 0; i < nums.size(); ++i) {
if (visited[i] == 0) {
if(i != 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0) continue;
cand.push_back(nums[i]);
visited[i] = 1;
dfs(nums, ans, cand, visited);
visited[i] = 0;
cand.pop_back();
}
}
}

public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
vector<int> cand, visited(nums.size(), 0);
dfs(nums, ans, cand, visited);
return ans;
}
};
```