**[Lintcode]Permutation Sequence 第k个排列

Given n and k, return the k-th permutation sequence.

Example

For n = 3, all permutations are listed as follows:

"123"
"132"
"213"
"231"
"312"
"321"

If k = 4, the fourth permutation is "231"

分析:如k = 4时,首位数字为 2, 即(k-1)/(k-1)! + 1.字面理解就是想要找的序列位置除以k-1位的全排列(2位数全排列,12,21共两种)的长度,即为k处数字所在的位置(注意不是数字的值,而是1~n中,除去已经出现过得数字后的index)。


class Solution {
    /**
      * @param n: n
      * @param k: the kth permutation
      * @return: return the k-th permutation
      */
    public String getPermutation(int n, int k) {
        String res = "";
        k -= 1;
        boolean[] s = new boolean[n];
        for(int i = n - 1; i >= 0; i--) {
            int j = i, tmp = 1;
            while(j > 0) {tmp *= j;j--;}
            int val = find((int)(k / tmp) + 1, s);
            res += val;
            s[val - 1] = true;
            k %= tmp;
        }
        return res;
    }

    int find(int a, boolean[] b) {
        int t = 0;
        for(int i = 0; i < b.length; i++) {
            if(b[i] == false) {
                t += 1;
                if(t == a) return i + 1;
            }
        }
        return -1;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值