forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations-ii.cpp
37 lines (33 loc) · 1.05 KB
/
permutations-ii.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Time: O(n * n!)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
vector<vector<int>> permuteUnique(vector<int> &nums) {
vector<vector<int>> result;
deque<bool> used(nums.size(), false);
vector<int> ans;
sort(nums.begin(), nums.end());
permuteUniqueRecu(nums, &used, &ans, &result);
return result;
}
void permuteUniqueRecu(const vector<int> &A, deque<bool> *used,
vector<int> *ans, vector<vector<int>> *result) {
if (ans->size() == A.size()) {
result->emplace_back(*ans);
return;
}
for (size_t i = 0; i < A.size(); ++i) {
if (!(*used)[i] && !(i != 0 && A[i - 1] == A[i] && (*used)[i - 1])) {
(*used)[i] = true;
ans->emplace_back(A[i]);
permuteUniqueRecu(A, used, ans, result);
ans->pop_back();
(*used)[i] = false;
}
}
}
};