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.
Solution:
public class Solution {
public String getPermutation(int n, int k) {
if(n==1&&k==1)
return "1";
int total=getTotal(n);
String original=getOriginal(n);
char[] result=new char[n];
for(int i=0;i<n;++i){
total/=(n-i);
int t2=(k-1)/total;
result[i]=original.charAt(t2);
original=original.replace(result[i]+"", ""); //这个方法很巧妙啊,用此法就可以把用过的数字从数组里去掉了!!!
k-=t2*total;
}
return new String(result);
} private String getOriginal(int n) {
// TODO Auto-generated method stub
String result="";
for(int i=1;i<=n;++i){
result+=i+"";
}
return result;
} private int getTotal(int n) {
// TODO Auto-generated method stub
int total=1;
for(int i=1;i<=n;++i){
total*=i;
}
return total;
}
}