# 047. Permutations II

Difficulty: Medium

Frequency: N/A

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

My solution:
Data structure:
Steps:
Complexity:
Runtime:
Space:
Test cases:
Corner cases:
Code:
```class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> results;
vector<int> tmp;
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
permuteHelper(nums, used, tmp, results);
return results;
}
void permuteHelper(vector<int> nums, vector<bool> used, vector<int> tmp, vector<vector<int>> &results) {
if(tmp.size() == nums.size()) {
results.push_back(tmp);
return;
}
for (int i = 0; i < nums.size(); i++) {
if(used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
tmp.push_back(nums[i]);
permuteHelper(nums, used, tmp, results);
tmp.pop_back();
used[i] = false;
}
}
};
```

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:
1. How to skip duplicate element
2. Avoid using lookup from previous result set.

# 089. Gray Code

Difficulty: Medium

Frequency: N/A

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return `[0,1,3,2]`. Its gray code sequence is:

```00 - 0
01 - 1
11 - 3
10 - 2
```

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, `[0,2,3,1]` is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

My solution:
Data structure:
vector
Steps:
Complexity:
Runtime:
Space:
Test cases:
Corner cases:
Code:
```class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
result.push_back(0);
for (int i = 0; i < n; i++) {
int highBit = 1 << i;
for (int j = result.size() - 1; j >= 0; j--) {
result.push_back(highBit + result[j]);
}
}
return result;
}
};
```

Another solution:
Data structure:
steps:
Complexity:
Runtime:
Space:
Code:

Things to learn:
1. How to do it in backtracking way?