-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpermutations.cpp
47 lines (41 loc) · 1023 Bytes
/
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
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void permute_recursive(vector<int>& nums, int start, vector<vector<int>>& result)
{
//base case
if (start >= (int) nums.size())
{
result.push_back(nums);
return;
}
//recursion
for (int i = start; i < (int) nums.size(); ++i)
{
swap(nums[start], nums[i]);
permute_recursive(nums, start+1, result);
swap(nums[start], nums[i]);
}
}
vector<vector<int>> permute(vector<int>& nums)
{
vector<vector<int>> result;
permute_recursive(nums, 0, result);
return result;
}
int main()
{
vector<int> nums = {1, 2, 3};
vector<vector<int>> permutations = permute(nums); //O(n!)
cout << "all possible permutations" << endl;
for (int i = 0; i < (int) permutations.size(); ++i)
{
for (int j = 0; j < (int) permutations[0].size(); ++j)
{
cout << permutations[i][j] << " ";
}
cout << endl;
}
return 0;
}