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 (ie, 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.
找第k大的数,类似于进位,10进制则是每次除10,这个相当于每次除n-1-i,然后第k个,则按计算机类从0记起,k-=1。
public class Solution {
public String getPermutation(int n, int k) {
if(n<1)
return "";
char[] chars = new char[n];
List<Character> list = new ArrayList<Character>();
for(int i=0;i<n;i++)
list.add((char)('1'+i));
int sum =1;
for(int i=1;i<n;i++)
sum*=i;
k-=1;
for(int i=0;i<n-1;i++){
chars[i]=list.get(k/sum);
list.remove(k/sum);
k%=sum;
sum/=n-1-i;
}
chars[n-1]=list.get(0);
return new String(chars);
}
}