# 47. Permutations II

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

```cpp
void helper(vector<int>& nums, int level, vector<int>& cur, vector<vector<int> >& res, vector<int>& visited) {
    if (level >= nums.size()) {
        res.push_back(cur);
    } else {
        for (int i = 0; i < nums.size(); ++i) {
            if (visited[i] == 1) continue;
            if (i > 0 && nums[i] == nums[i - 1] && visited[i - 1] == 0) continue;
            visited[i] = 1;
            cur.push_back(nums[i]);
            helper(nums, level + 1, cur, res, visited);
            cur.pop_back();
            visited[i] = 0;
        }
    }
}
vector<vector<int>> permuteUnique(vector<int>& nums) { // time: O(n!); space: O(n!)
    sort(nums.begin(), nums.end());
    vector<vector<int> > res;
    vector<int> cur, visited(nums.size(), 0);
    helper(nums, 0, cur, res, visited);
    return res;
}
```

{% content-ref url="46.-permutations" %}
[46.-permutations](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/backtracking/46.-permutations)
{% endcontent-ref %}
