Paint Fence

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.

递归

复杂度

O(N) 时间 O(N) 空间

思路

举例:n=3找第5个
递归退出条件:n=1,一个数只能返回一个,就是他自己
对于(n,k),表示n个数的全排列里找第k个,这n个数放在list里
这n个数构成了n个bucket,每个bucket大小相等,我们可以知道第k个在哪个bucket里。
每个bucket对应一个List里的数字。append到答案里,把这个bucket从list删掉。
最后更新k,让k表示在新桶里的第几小,n减一,继续迭代。

注意

求一个桶多大的时候,要求n!,递归求会超时,用int[]记录下来就好,最多10个数,所以很经济。

代码

public class Solution {
    public String getPermutation(int n, int k) {
        StringBuilder sb = new StringBuilder();
        List<Integer> list = new ArrayList<Integer>();
        int[] factTable = new int[10];
        factTable[1] = 1;
        for (int i = 2; i <= 9; i++) {
            factTable[i] = factTable[i - 1] * i;
        }
        for (int i = 1; i <= n; i++)
            list.add(i);
        helper(n, k, list, sb, factTable);
        return sb.toString();
    }
    public void helper(int n, int k, List<Integer> list, StringBuilder sb, int[] factTable) {
        if (n == 1) {
            sb.append(list.get(0));
            return;
        }
        int fact = factTable[n - 1];
        int bucket = (k - 1) / fact;
        sb.append(list.get(bucket));
        list.remove(bucket);
        helper(n - 1, k - fact * bucket, list, sb, factTable);
    }
}

liuqi627
364 声望100 粉丝