-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path47.permutations-ii.cpp
More file actions
74 lines (71 loc) · 1.86 KB
/
47.permutations-ii.cpp
File metadata and controls
74 lines (71 loc) · 1.86 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* @lc app=leetcode id=47 lang=cpp
*
* [47] Permutations II
*
* https://leetcode.com/problems/permutations-ii/description/
*
* algorithms
* Medium (37.56%)
* Likes: 1392
* Dislikes: 48
* Total Accepted: 291.6K
* Total Submissions: 675K
* Testcase Example: '[1,1,2]'
*
* 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]
* ]
*
*
*/
// @lc code=start
class Solution {
public:
void permuteUniqueHelper(vector<int>& nums, vector<bool>& used,
vector<int>& buffer, int buffer_index,
vector<vector<int>>& return_vector) {
if (buffer_index == buffer.size()) {
return_vector.push_back(buffer);
return;
}
for (int i = 0; i < nums.size(); ++i) {
// NOW we are picking a number to fill our buffer
// Make sure that the number being picked hasnt been used to partially
// fill the buffer before this
if (!used[i]) {
used[i] = true;
buffer[buffer_index] = nums[i];
permuteUniqueHelper(nums, used, buffer, buffer_index + 1,
return_vector);
used[i] = false;
}
// we would also like to skip some future numbers:
// skip all numbers that are the same as the current element UNLESS you
// encounter a
while (!used[i] && i + 1 < nums.size() && nums[i] == nums[i + 1]) {
++i;
}
}
return;
}
vector<vector<int>> permuteUnique(vector<int>& nums) {
std::sort(nums.begin(), nums.end());
vector<vector<int>> return_vector;
vector<int> buffer(nums.size(), 0);
vector<bool> used(nums.size(), false);
permuteUniqueHelper(nums, used, buffer, 0, return_vector);
return return_vector;
}
};
// @lc code=end