-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46.permutations.cpp
36 lines (34 loc) · 944 Bytes
/
46.permutations.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
/*
* @lc app=leetcode id=46 lang=cpp
*
* [46] Permutations
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> permute(vector<int>& nums) {
sort(nums.begin(), nums.end());
backtracking({}, nums);
return ans;
}
void backtracking(vector<int> combination, vector<int> remains) {
if (remains.empty()) {
ans.push_back(combination);
return;
} else {
set<int> s;
for (auto it = remains.begin(); it < remains.end(); it++) {
int value = *it;
if (s.count(value)) continue;
s.insert(value);
remains.erase(it);
combination.push_back(value);
backtracking(combination, remains);
combination.pop_back();
remains.insert(it, value);
}
}
}
};
// @lc code=end