您的位置:首页 > 产品设计 > UI/UE

[LeetCode]60. Permutation Sequence

2017-01-09 10:50 357 查看
https://leetcode.com/problems/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.

康托展开



其中,{\displaystyle a_{i}}

为整数,并且{\displaystyle
0\leq a_{i}<i,1\leq i\leq n}



{\displaystyle a_{i}}

的意义参见举例中的解释部分


举例[编辑]

例如,3 5 7 4 1 2 9 6 8 展开为 98884。因为X=2*8!+3*7!+4*6!+2*5!+0*4!+0*3!+2*2!+0*1!+0*0!=98884.

解释:

排列的第一位是3,比3小的数有两个,以这样的数开始的排列有8!个,因此第一项为2*8!

排列的第二位是5,比5小的数有1、2、3、4,由于3已经出现,因此共有3个比5小的数,这样的排列有7!个,因此第二项为3*7!

以此类推,直至0*0!

用nums保存剩余还未取的数字,用k找到当前位要在剩余数字里面选择第几个(从零开始数),因为是从零开始数,所以先把k减一,这样再做除法就是得到取下界结果

public class Solution {
public String getPermutation(int n, int k) {
StringBuilder sb = new StringBuilder();
LinkedList<Integer> nums = new LinkedList();
int factor = 1;
for (int i = 1; i <= n; i++) {
factor *= i;
nums.add(i);
}
// 把k减一,然后再去做除法,得到的结果就是取下界
for (int i = 0, l = k - 1; i < n; i++) {
factor /= (n - i);
int index = (l / factor);
sb.append(nums.remove(index));
l -= index * factor;
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: