File tree Expand file tree Collapse file tree 1 file changed +27
-21
lines changed Expand file tree Collapse file tree 1 file changed +27
-21
lines changed Original file line number Diff line number Diff line change
1
+ #include <stdbool.h>
1
2
#include <stdio.h>
2
3
#include <stdlib.h>
3
4
#include <string.h>
4
5
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
-
16
6
static char * getPermutation (int n , int k )
17
7
{
18
8
int i ;
19
- int * permutation = malloc (n * sizeof (int ));
20
- for (i = 0 ; i < n ; i ++ ) {
21
- permutation [i ] = i + 1 ;
22
- }
23
-
24
9
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 */
25
19
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' ;
31
36
}
37
+
32
38
result [n ] = '\0' ;
33
39
return result ;
34
40
}
You can’t perform that action at this time.
0 commit comments