-
Notifications
You must be signed in to change notification settings - Fork 0
/
46-permutations.cpp
69 lines (60 loc) · 2.21 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
57
58
59
60
61
62
63
64
65
66
67
68
69
// Title: Permutations
// Description:
// Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
// Link: https://leetcode.com/problems/permutations/
// Time complexity: O(n*n!)
// Space complexity: O(n*n!)
template<typename T>
class MyListNode {
public:
T data;
MyListNode<T> *next;
MyListNode(T data): data(data), next(NULL) {}
};
class Solution {
public:
std::vector<std::vector<int>> permute(std::vector<int> &nums) {
// build a linklist of nums with a dummy head node
MyListNode<int> *dummyHead = new MyListNode<int>(0xDEADBEEF); {
MyListNode<int> *prevNode = dummyHead;
for (int num: nums) {
prevNode->next = new MyListNode<int>(num);
prevNode = prevNode->next;
}
}
std::vector<int> currentPermutation;
std::vector<std::vector<int>> results;
std::function<void ()> backtrack = [&]() {
// the permutation is finished if there is no more choice
if (dummyHead->next == NULL) {
results.push_back(currentPermutation);
return;
}
// select each choice and permute the remaining choices
for (
MyListNode<int> *prevNode = dummyHead, *currentNode = dummyHead->next;
currentNode != NULL;
prevNode = currentNode, currentNode = currentNode->next
) {
currentPermutation.push_back(currentNode->data);
prevNode->next = currentNode->next;
backtrack();
prevNode->next = currentNode;
currentPermutation.pop_back();
}
};
// start backtracking
backtrack();
// free allocated memory
for (
MyListNode<int> *currentNode = dummyHead, *nextNode;
currentNode != NULL;
currentNode = nextNode
) {
nextNode = currentNode->next;
delete currentNode;
}
return results;
}
/* There is an (unordered) in-place algorithm that operates like Fisher–Yates shuffle */
};