-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathGenerate permutation
More file actions
77 lines (62 loc) · 1.29 KB
/
Generate permutation
File metadata and controls
77 lines (62 loc) · 1.29 KB
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
73
74
75
76
77
#include<bits/stdc++.h>
using namespace std;
//========================= USING HASH MAP ===========================================================//
void generatepermutation(vector<vector<int>> &ans,vector<int> &frenquecy,vector<int> &v,vector<int>ds )
{
if(ds.size()==v.size())
{
return ans.push_back(ds);
}
for(int i=0;i<v.size();i++)
{
if(frenquecy[i]==0)
{
ds.push_back(v[i]);
frenquecy[i]=1;
generatepermutation(ans,frenquecy,v,ds);
frenquecy[i]=0;
ds.pop_back();
}
}
}
// time complexity : O(n! * n)
// space complexity : O(n)+O(n)
//========================================Aprroach 2==================================================
void generatepermutation2(vector<vector<int>> &ans,int index,vector<int> &v)
{
if(index==v.size())
{
ans.push_back(v);
return;
}
for(int i=index;i<v.size();i++)
{
swap(v[i],v[index]);
generatepermutation2(ans,index+1,v);
swap(v[i],v[index]);
}
// time complexity : O(n! * n)
// space complexity : O(n)
}
int main()
{
vector<vector<int>> ans;
vector<int> ds,v;
int n;
cin>>n;
vector<int> frenquecy(n,0);
while(n--)
{
int x;
cin>>x;
v.push_back(x);
}
//generatepermutation(ans,frenquecy,v,ds);
generatepermutation2(ans,0,v);
for(auto x:ans)
{
for(auto y:x)
cout<<y<<" ";
cout<<endl;
}
}