-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneratePermutationOfN.cpp
More file actions
51 lines (46 loc) · 968 Bytes
/
GeneratePermutationOfN.cpp
File metadata and controls
51 lines (46 loc) · 968 Bytes
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
/*
Problem: Permutation generation
Description
Given an integer n, write a program to generate all permutations of 1, 2, ..., n in a lexicalgraphic order (elements of a permutation are separated by a SPACE character).
Example
Input
3
Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
#include<bits/stdc++.h>
using namespace std;
int n;
vector<int> permutations(n+1);
vector<int> isMarked(n+1, 0);
void Try(int k) {
for (int i = 1; i <= n; i++)
{
if (isMarked[i]==0)
{
permutations[k] = i;
isMarked[i] = 1;
if (k == n)
{
for (int j = 1; j <= n; j++)
{
printf("%d ", permutations[j]);
}
printf("\n");
} else Try(k+1);
isMarked[i] = 0;
}
}
}
int main() {
cin >> n;
permutations.resize(n+1);
isMarked.resize(n+1, 0);
Try(1);
return 0;
}