-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path46.permutations.cpp
57 lines (45 loc) · 1.28 KB
/
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @lc app=leetcode id=46 lang=cpp
*
* [46] Permutations
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> result;
// selected list, path
stack<pair<vector<int>, vector<int>>> stk;
for(int i = 0; i < nums.size(); i++) {
stk.push({ vector<int> {nums[i]}, vector<int>{i} });
}
while(!stk.empty()) {
vector<int> selectedList = stk.top().first;
vector<int> path = stk.top().second;
stk.pop();
if(selectedList.size() == nums.size()) {
result.push_back(selectedList);
continue;
}
for (int i = 0; i < nums.size(); i++) {
if(find(path.begin(), path.end(), i) == path.end()){
selectedList.push_back(nums[i]);
path.push_back(i);
stk.push({ selectedList, path });
selectedList.pop_back();
path.pop_back();
}
}
}
return result;
}
};
// @lc code=end