-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy path35-permutation-decrease-conquer.c
More file actions
65 lines (50 loc) · 973 Bytes
/
Copy path35-permutation-decrease-conquer.c
File metadata and controls
65 lines (50 loc) · 973 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
Uses the definition of n! to generate the permutations.
Idea:
-----
Remove each item from the given n items one at a time and
append it to remaining (n-1)! permutations.
Efficiency:
-----------
O(n!) and as well we have expensive swaps
Strategy used:
--------------
Decrease and Conquer(decrease by 1)
*/
#include <stdio.h>
#include <stdlib.h>
// Global n
int gn;
void permute(int a[], int n)
{
if (n == 1)
{
int i;
for(i = 0; i < gn; i++)
printf("%d ", a[i]);
printf("\n");
return;
}
int i;
int temp;
for(i = 0; i < n; i++)
{
// Remove the ith item
temp = a[i];
a[i] = a[n-1];
a[n-1] = temp;
permute(a, n-1);
// Restore it for the next round
temp = a[i];
a[i] = a[n-1];
a[n-1] = temp;
}
}
int main()
{
int a[5] = {1, 2, 3};
int n = 3;
gn = n;
permute(a, n);
return 0;
}