Skip to content

Commit ef086eb

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 4f58f7f commit ef086eb

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

060_permutation_sequence/permutation_sequence.c

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,40 @@
1+
#include <stdbool.h>
12
#include <stdio.h>
23
#include <stdlib.h>
34
#include <string.h>
45

5-
static int factorial(int n)
6-
{
7-
if (n == 0) {
8-
return 0;
9-
} else if (n == 1) {
10-
return 1;
11-
} else {
12-
return n * factorial(n - 1);
13-
}
14-
}
15-
166
static char* getPermutation(int n, int k)
177
{
188
int i;
19-
int *permutation = malloc(n * sizeof(int));
20-
for (i = 0; i < n; i++) {
21-
permutation[i] = i + 1;
22-
}
23-
249
char *result = malloc(n + 1);
10+
bool *used = malloc(n * sizeof(bool));
11+
memset(used, false, n * sizeof(bool));
12+
13+
int total = 1;
14+
for (i = 1; i <= n; i++) {
15+
total *= i; /* n! */
16+
}
17+
18+
k = k - 1; /* Begin with 0 */
2519
for (i = 0; i < n; i++) {
26-
int fac = factorial(n - i - 1);
27-
int j = k > 1 ? (k - 1) / fac : 0;
28-
result[i] = permutation[j] + '0';
29-
k -= j * fac;
30-
memmove(permutation + j, permutation + j + 1, (n - j) * sizeof(int));
20+
/* Total elements in each group */
21+
total /= (n - i);
22+
int gid = k / total;
23+
k %= total;
24+
25+
int x = -1;
26+
int count = 0;
27+
/* Search in the remaining numbers */
28+
while (count <= gid) {
29+
x = (x + 1) % n;
30+
if (!used[x]) {
31+
count++;
32+
}
33+
}
34+
used[x] = true;
35+
result[i] = x + 1 + '0';
3136
}
37+
3238
result[n] = '\0';
3339
return result;
3440
}

0 commit comments

Comments
 (0)