-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations of Strings
More file actions
52 lines (51 loc) · 1013 Bytes
/
Permutations of Strings
File metadata and controls
52 lines (51 loc) · 1013 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** a, char** b)
{
char* temp = *a;
*a = *b;
*b = temp;
}
void reverse(char** s, int start, int end)
{
while (start < end) {
swap(s + start++, s + end--);
}
}
int next_permutation(int n, char** s)
{
for (int i = n - 2; i >= 0; --i) {
if (strcmp(s[i], s[i + 1]) < 0) {
for (int j = n - 1; j > i; --j) {
if (strcmp(s[i], s[j]) < 0) {
swap(s + i, s + j);
reverse(s, i + 1, n - 1);
return 1;
}
}
}
}
return 0;
}
int main()
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char*));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}