forked from markandey007/DSA_CODES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermutations
45 lines (41 loc) · 795 Bytes
/
Permutations
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
#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> nums, vector<vector<int>> &ans, int i)
{
if (i >= nums.size())
{
ans.push_back(nums);
return;
}
for (int j = i; j < nums.size(); ++j)
{
swap(nums[i], nums[j]);
solve(nums, ans, i + 1);
// backtrack
swap(nums[i], nums[j]);
}
}
vector<vector<int>> permute(vector<int> &nums)
{
vector<vector<int>> ans;
solve(nums, ans, 0);
return ans;
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
vector<vector<int>> ans = permute(a);
for (auto i : ans)
{
for (auto j : i)
{
cout << j << " ";
}
cout << endl;
}
return 0;
}