Permutation Sequence
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是4,则当第一位确定的时候,后面三位总共有6种(3!)组合可能。当前两位决定的时候,后面两位总共有2种(2!)组合可能。
那么对于我们的k,我们需要判断k所在的位置,即x!<=(k-1)<(x+1)!,通过这样我们来确定前面那些部分是按照顺序排的(前n-x位),从哪开始就不是按照顺序排的。
假设说k = 7,n = 4,3!<=(k-1)<4!,这时可以看出从第一位开始就不是按顺序排的。再计算(k-1)/6 = 1。可以看出此时第一位被换成了第(1+1)位,即首位为2,将其取出。
令k = k%6 = 0。由于此时k = 0。说明之后的是按顺序排的,所以剩下的排序为134。合起来就是2134。大概的思路就是这样的....
我只能把我自己理解的大概这样讲了,剩下的就看代码吧
public class Solution {
public String getPermutation(int n, int k) {
List<String> num = new ArrayList<String>();
for (int i = 0;i<n;i++)
num.add(Integer.toString(i+1));
int x = k-1;
int index = 1;
int per = 1;
do
{
//找出满足(index-1)! <= x <index! 对应的index值
while(x>=per)
{
index++;
per *= index;
}
//把前面部分按照顺序排序
for(int i = 0;i<n-index;i++)
result += num.remove(0);
//将n改为index,表示还剩的没有排序的位数
n = index-1;
per /= index;
//n1表示此时剩下的没排序的第1位被换成剩下的数中的第几个
int n1 = x/per;
//更新x
x %= per;
//将第n1个值取出来
result += num.remove(n1);
//恢复初始值,重新查找
index = 1;
per = 1;
}while(x!= 0);
//剩下来的按照顺序排
while(!num.isEmpty())
result += num.remove(0);
return result;
}
}