-
Notifications
You must be signed in to change notification settings - Fork 0
/
44_permutations.cpp
72 lines (60 loc) · 1.28 KB
/
44_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
70
71
72
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> ans;
// for array having distinct elements
void permutations(vector<int> a, int ndx)
{
if (ndx == a.size())
{
ans.push_back(a);
return;
}
for (int i = ndx; i < a.size(); i++)
{
swap(a[i], a[ndx]);
permutations(a, ndx + 1);
swap(a[i], a[ndx]);
}
}
// for array having repeating elements
void permutations2(vector<int> a,int idx){
if(idx==a.size()){
ans.push_back(a);
return;
}
for(int i = idx;i<a.size();i++){
if(i!=idx && a[i]==a[idx])
continue;
swap(a[i],a[idx]);
permutations2(a,idx+1);
}
}
void permutations3(vector<int> a){
sort(a.begin(),a.end());
do{
ans.push_back(a);
}while(next_permutation(a.begin(),a.end()));
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (auto &i : a)
{
cin >> i;
}
permutations(a,0);
// sort(a.begin(),a.end());// its compulsory
// permutations2(a, 0);
// permutations3(a);
for (auto i : ans)
{
for (auto j : i)
{
cout << j << " ";
}
cout << endl;
}
return 0;
}