60. Permutation Sequence

来源:互联网 发布:淘宝联盟互刷 编辑:程序博客网 时间:2024/04/20 07:28

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.

public class Solution {    public String getPermutation(int n, int k) {        List<Integer> nums = new ArrayList<Integer>();        StringBuilder sb = new StringBuilder();        int fact = 1;        for(int i = 1; i <= n; i++){            fact *= i;            nums.add(i);        }        int l = k-1;        for(int i = 0; i < n; i++){            fact /= (n-i);            int index = l / fact;            sb.append(nums.remove(index));            l -= index*fact;        }        return sb.toString();    }}
0 0
原创粉丝点击