-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPermutations.cpp
47 lines (41 loc) · 1.05 KB
/
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
// Permutations
// https://leetcode.com/explore/interview/card/top-interview-questions-medium/109/backtracking/795/
#include <iostream>
#include <vector>
void permutations(std::vector<std::vector<int>>& result, std::vector<int>& nums, int begin)
{
if (begin >= nums.size()) {
result.push_back(nums);
return;
}
for (int i = begin; i < nums.size(); ++i) {
std::swap(nums[begin], nums[i]);
permutations(result, nums, begin + 1);
std::swap(nums[begin], nums[i]);
}
}
std::vector<std::vector<int>> permutation(std::vector<int>& nums)
{
std::vector<std::vector<int>> result;
permutations(result, nums, 0);
return result;
}
void print(std::vector<std::vector<int>> result)
{
if (result.size() == 0) {
return;
}
for (auto res : result) {
for (auto r : res) {
std::cout << r << " ";
}
std::cout << "\n";
}
}
int main()
{
std::vector<int> nums {1};
std::vector<std::vector<int>> result = permutation(nums);
print(result);
return 0;
}