Skip to content

Commit 55fd193

Browse files
committed
permutations
1 parent 2ee30f9 commit 55fd193

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Diff for: Permutations II.cpp

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Permutations II
2+
// method1: use hashmap to record and swap i with j( j = i .....n)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int> > permuteUnique(vector<int> &num) {
7+
vector<vector<int> > result;
8+
if(num.size()== 0) return result;
9+
vector<int> path;
10+
dfs(result, path, num, 0);
11+
return result;
12+
}
13+
void dfs(vector<vector<int> > &result, vector<int> &path, vector<int> &num, int index){
14+
if(index == num.size()){
15+
result.push_back(path);
16+
return;
17+
}
18+
unordered_set<int> hashmap;
19+
for(int i = index; i < num.size(); i++){
20+
// the element is not in hashmap
21+
if(hashmap.find(num[i]) == hashmap.end()){
22+
hashmap.insert(num[i]);
23+
swap(num[index], num[i]);
24+
path.push_back(num[index]);
25+
dfs(result, path, num, index + 1);
26+
path.pop_back();
27+
swap(num[index], num[i]);
28+
}
29+
}
30+
31+
}
32+
};

Diff for: permutation.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
vector<vector<int> > permute(vector<int> &num) {
4+
sort(num.begin(), num.end()); // sort
5+
vector<vector<int> > result; // final answer
6+
vector<int> path; // current path
7+
dfs(result, path, num); // depth first search
8+
return result;
9+
}
10+
private:
11+
void dfs(vector<vector<int> > &result, vector<int> &path, vector<int> &num){
12+
if(path.size() == num.size()){ // find one path
13+
result.push_back(path);
14+
return;
15+
}
16+
for(auto i: num){
17+
auto pos = find(path.begin(), path.end(), i); // return the pos or the last
18+
if(pos == path.end()){
19+
path.push_back(i);
20+
dfs(result, path, num);
21+
path.pop_back();
22+
}
23+
}
24+
25+
}
26+
};

0 commit comments

Comments
 (0)