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

leetcode 60. Permutation Sequence

2016-09-19 22:10 246 查看
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.

12345:
1开头的有4!=24种
2开头的有24种
3开头。。
4开头。。
5开头。。
如果24<K<48 那就是2开头的
进而2开头的里面  1345:1开头的有3!=6种
3开头的有6种。。
4开头。。
5开头。。
所以124:
124/4!  确定第一个字符
124%4!/3! 确定第二个字符


public String getPermutation(int n, int k) {
StringBuffer sb = new StringBuffer();
List<Integer> integers = new ArrayList<Integer>();
int[] factorials = new int
;
factorials[0] = 1;
for(int i = 1;i < n;i++) {factorials[i] = i * factorials[i-1]; integers.add(i);}
integers.add(n);
n--;
while(n>=0){
int temp = (k-1)/factorials
;
sb.append(integers.get(temp));
integers.remove(temp);
integers.sort((a,b)->(a-b));
k = k % factorials
==0 ? factorials
: k % factorials
;
n--;
}
return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: