使用 领扣中国,来获得适合您的内容以及最佳的用户体验。
即刻前往 | 将我的账号同步到 LeetCode 中国
LeetCode
Explore
Problems
Mock
Contest
Articles
Discuss
Store
Premium
New Playground
lifeqiuzhi520
60. Permutation Sequence
DescriptionHintsSubmissionsDiscussSolution
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
Seen this question in a real interview before?
Difficulty:Medium
Total Accepted:113.4K
Total Submissions:369.9K
Contributor:LeetCode
Subscribe to see which companies asked this question.
Related Topics
Similar Questions
Next PermutationPermutations
Java
public String getPermutation(int n, int k) {
int[] array = new int[n];
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
data = k;
getPermutation(array, k, new ArrayList<Integer>(), n);
return text;
}
private int data;
private String text = "";
private String getPermutation(int[] array, int k, ArrayList<Integer> i, int n) {
for (int j = 0; j < array.length; j++) {
int temp = array[j];
i.add(temp);
int[] ints = null;
if (array.length == 1) {
data--;
if (data == 0) {
for (Integer integer : i) {
text = new StringBuilder().append(text).append(integer).toString();
}
}
i.remove(i.size() - 1);
return Arrays.toString(i.toArray());
} else {
if (j == 0) {
ints = Arrays.copyOfRange(array, 1, array.length);
} else {
ints = new int[array.length - 1];
System.arraycopy(array, 0, ints, 0, j);
if (j + 1 < array.length) {
System.arraycopy(array, j + 1, ints, j, array.length - j - 1);
}
}
getPermutation(ints, k - 1, i, n);
i.remove(i.size() - 1);
}
}
return "";
}
1
class Solution {
2
public String getPermutation(int n, int k) {
3
int pos = 0;
4
List<Integer> numbers = new ArrayList<>();
5
int[] factorial = new int[n+1];
6
StringBuilder sb = new StringBuilder();
7
8
// create an array of factorial lookup
9
int sum = 1;
10
factorial[0] = 1;
11
for(int i=1; i<=n; i++){
12
sum *= i;
13
factorial[i] = sum;
14
}
15
// factorial[] = {1, 1, 2, 6, 24, ... n!}
16
17
// create a list of numbers to get indices
18
for(int i=1; i<=n; i++){
19
numbers.add(i);
20
}
21
// numbers = {1, 2, 3, 4}
22
23
k--;
24
25
for(int i = 1; i <= n; i++){
26
int index = k/factorial[n-i];
27
sb.append(String.valueOf(numbers.get(index)));
28
numbers.remove(index);
29
k-=index*factorial[n-i];
30
}
31
32
return String.valueOf(sb);
33
}
34
}
Custom Testcase( Contribute )
Submission Result: Accepted
Next challenges: Strobogrammatic Number IIFactor CombinationsSolve the Equation
Share your acceptance!
6
Type here...(Markdown is enabled)
Copyright © 2018 LeetCode Contact Us | Jobs | Students | Frequently Asked Questions | Terms of Service | Privacy Policy United States