forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.cpp
More file actions
65 lines (61 loc) · 1.48 KB
/
Permutations.cpp
File metadata and controls
65 lines (61 loc) · 1.48 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
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 10, 2012
Problem: Permutations
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
Solution:
There is a same time complexity but with more simple code solution provided by
https://github.com/anson627/leetcode/blob/master/Permutations/src/Permutations.cpp
All permutations can be generated by swapping.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <list>
using namespace std;
class Solution {
public:
bool *available;
vector<vector<int> > result;
vector<int> permutation;
int n;
void recursion(int dep, vector<int> &num) {
if (dep == n) {
result.push_back(permutation);
return;
}
int i = 0;
while (i < n) {
if (available[i]) {
available[i] = false;
permutation.push_back(num[i]);
recursion(dep + 1, num);
available[i] = true;
permutation.pop_back();
}
i++;
}
}
vector<vector<int> > permute(vector<int> &num) {
vector<int> permutation;
n = num.size();
available = new bool[n];
for (int i = 0; i < n; i++) {
available[i] = true;
}
result.clear();
recursion(0, num);
return result;
}
};