-
Notifications
You must be signed in to change notification settings - Fork 1
/
PermutationsOfStringsHR.c
111 lines (90 loc) · 2.49 KB
/
PermutationsOfStringsHR.c
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
Strings are usually ordered in lexicographical order. That means they are ordered by comparing their leftmost different characters. For example, because . Also because . If one string is an exact prefix of the other it is lexicographically smaller, e.g., .
Given an array of strings sorted in lexicographical order, print all of its permutations in strict lexicographical order. If two permutations look the same, only print one of them. See the 'note' below for an example.
Complete the function next_permutation which generates the permutations in the described order.
For example, . The six permutations in correct order are:
ab bc cd
ab cd bc
bc ab cd
bc cd ab
cd ab bc
cd bc ab
Note: There may be two or more of the same string as elements of .
For example, . Only one instance of a permutation where all elements match should be printed. In other words, if , then print either or but not both.
A three element array having three discrete elements has six permutations as shown above. In this case, there are three matching pairs of permutations where and are switched. We only print the three visibly unique permutations:
ab ab bc
ab bc ab
bc ab ab
Input Format
The first line of each test file contains a single integer , the length of the string array .
Each of the next lines contains a string .
Constraints
contains only lowercase English letters.
Output Format
Print each permutation as a list of space-separated strings on a single line.
Sample Input 0
2
ab
cd
Sample Output 0
ab cd
cd ab
Sample Input 1
3
a
bc
bc
Sample Output 1
a bc bc
bc a bc
bc bc a
Explanation 1
This is similar to the note above. Only three of the six permutations are printed to avoid redundancy in output.
*/
// SOLUTION
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int next_permutation(int n, char **s)
{
int i = n-1;
while(i>0 && strcmp(s[i-1],s[i])>=0)
i--;
if (i<=0) return 0;
int j = n-1;
while(strcmp(s[i-1],s[j])>=0)
j--;
char *tmp = s[i-1];
s[i-1] = s[j];
s[j] = tmp;
j = n-1;
while(i<j) {
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
return 1;
}
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;
}