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

LeetCode_OJ【60】Permutation Sequence

2016-02-20 11:06 369 查看
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.

这道题目的思路比较简单,但是在写的时候还是有一些细节要注意。

第K个数在sequenc中的序号为k-1。n-1个数的全排列个数为(n-1)!,(k-1)/(n-1)!得到的就是String中第一个数字在set中的位置。

比如此题中给定输入n =3,k = 5。(k-1)/(n-1)! =2,而set中序号为2的数字是3。由此思路可以一直求下去得到结果。

public String getPermutation(int n, int k) {
List<Integer> list = new ArrayList<Integer>();
List<Integer> fact = new ArrayList<Integer>();
for(int i = 0 ; i < n ; i ++){
list.add(i+1);
if(i == 0 || i == 1)
fact.add(1);
else
fact.add(fact.get(i-1)*i);
}
String res ="";
k--;
while(n > 0){
res += list.remove(k/fact.get(n-1));
k = k % fact.get(n-1);
n--;
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode