Skip to content

Commit e067afb

Browse files
committed
Permutation Sequence
1 parent d478cd6 commit e067afb

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

PermutationSequence.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* The set [1,2,3,¡­,n] contains a total of n! unique permutations.
3+
*
4+
* By listing and labeling all of the permutations in order,
5+
* We get the following sequence (ie, for n = 3):
6+
*
7+
* "123"
8+
* "132"
9+
* "213"
10+
* "231"
11+
* "312"
12+
* "321"
13+
* Given n and k, return the kth permutation sequence.
14+
*
15+
* Note: Given n will be between 1 and 9 inclusive.
16+
*
17+
*/
18+
19+
public class PermutationSequence {
20+
public String getPermutation(int n, int k) {
21+
char[] arr = new char[n];
22+
int pro = 1;
23+
for (int i = 0; i < n; ++i) {
24+
arr[i] = (char) ('1' + i);
25+
pro *= (i + 1);
26+
}
27+
k = k - 1;
28+
k %= pro;
29+
pro /= n;
30+
for (int i = 0; i < n - 1; ++i) {
31+
int selectI = k / pro;
32+
k = k % pro;
33+
pro /= (n - i - 1);
34+
int temp = arr[selectI + i];
35+
for (int j = selectI; j > 0; --j) {
36+
arr[i + j] = arr[i + j - 1];
37+
}
38+
arr[i] = (char) temp;
39+
}
40+
return String.valueOf(arr);
41+
}
42+
}

0 commit comments

Comments
 (0)