Skip to content

Commit d1ce520

Browse files
Create PermutationsOfStrings.c
1 parent 43a8195 commit d1ce520

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Functions/PermutationsOfStrings.c

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <string.h>
4+
5+
void swap(char **s, int i, int j)
6+
{
7+
char * tmp = s[i];
8+
s[i] = s[j];
9+
s[j] = tmp;
10+
}
11+
12+
void reverse(char **s, int start, int end)
13+
{
14+
while(start<end)
15+
{
16+
swap(s,start++,end--);
17+
}
18+
}
19+
20+
int next_permutation(int n, char **s)
21+
{
22+
for(int i=n-2;i>-1;i--)
23+
{
24+
if(strcmp(s[i+1],s[i])>0)
25+
{
26+
//get min max
27+
for(int j=n-1;j>i;j--)
28+
{
29+
if(strcmp(s[j],s[i])>0)
30+
{
31+
//do swap
32+
swap(s,i,j);
33+
// do reverse
34+
reverse(s,i+1,n-1);
35+
return 1;
36+
}
37+
}
38+
}
39+
}
40+
return 0;
41+
}
42+
int main()
43+
{
44+
char **s;
45+
int n;
46+
scanf("%d", &n);
47+
s = calloc(n, sizeof(char*));
48+
for (int i = 0; i < n; i++)
49+
{
50+
s[i] = calloc(11, sizeof(char));
51+
scanf("%s", s[i]);
52+
}
53+
do
54+
{
55+
for (int i = 0; i < n; i++)
56+
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
57+
} while (next_permutation(n, s));
58+
for (int i = 0; i < n; i++)
59+
free(s[i]);
60+
free(s);
61+
return 0;
62+
}

0 commit comments

Comments
 (0)