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.
题目:把1~n按照字典序列排列,返回第K个字符串。
思路:题目已经说明,有n!个字符串,那n-1个数,则有(n-1)!个字符串,所以最高位确定,一共有(n-1)!个字符串,这就可以把n!个字符串分组。k/n!就可以确定一位数字,k = k%n!寻找下一位。
public String getPermutation(int n, int k) {
k--;//to transfer it as begin from 0 rather than 1
List<Integer> numList = new ArrayList<Integer>();
for(int i = 1; i<= n; i++)
numList.add(i);
int factorial = 1;
for(int i = 2; i < n; i++)
factorial *= i;
StringBuilder res = new StringBuilder();
int times = n-1;
while(times>=0){
int indexInList = k/factorial;
res.append(numList.get(indexInList));
numList.remove(indexInList);
k = k%factorial;//new k for next turn
if(times!=0)
factorial = factorial/times;//new (n-1)!
times--;
}
return res.toString();
}