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.
这道题是个比较巧妙的问题,但并不是很难。
首先确定第一个数。因为是n的数的全排列,第一个数确定之后,剩下的数共有(n-1)!种可能性。所以要计算出第 kth 个全排列含有多少个(n-1)!了,比如有m个,那么第一个数就应该是m+1. 之后再确定第二个数,和第一个思路一样,只不过k要变成 k - m * (n-1)! ,如此循环即可。
PS. 用一个布尔数组标记这个数是否被用过,用过的话直接跳过。代码如下:
public class Solution {
public String getPermutation(int n, int k) {
int[] fac = { 1,1,2,6,24,120,720,5040,40320,362880};
boolean[] flags = new boolean[n];
StringBuilder st = new StringBuilder();
getPermutation(st, flags, fac, n, k);
return st.toString();
}
private void getPermutation(StringBuilder st, boolean[] flags, int[] fac, int n, int k) {
// TODO Auto-generated method stub
while(true){
if(n == 1){
for(int i = 0; i < fac.length; i++ ){
if(flags[i] == false){
st.append(i+1);
return;
}
}
}
int level = (k-1)/fac[n-1];
k = k - level * fac[n-1];
for(int i = 0; i < fac.length; i++){
if(flags[i] == false){
if(level == 0){
st.append(i+1);
flags[i] = true;
break;
}
level--;
}
}
n--;
}
}
}