leetcode解题方案--060--Permutation Sequence

题目

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.

分析

我的思路很奇怪
用递归。
- 先判断第k个排序会影响到哪一位
- 得到三个值,分别代表变动的数字个数,前一位增长值和下一次递归的k

class Solution {
    public static String getPermutation(int n, int k) {
        k = k-1;
        int [] cons = new int[11];
        cons[0] = 1;
        cons[1] = 1;
        for (int i = 2; i<=10; i++) {
            cons[i] = i*cons[i-1];
        }
        int[] array = new int[n];
        for (int i =0; i<n; i++) {
            array[i] = i+1;
        }
        StringBuffer ret = new StringBuffer("");
        getkIndex(ret, array, k, cons);

        return ret.toString();
    }
    public static void getkIndex(StringBuffer xx, int[] array, int k, int[] cons) {
        Arrays.sort(array);
        int length = array.length;
        if (length ==1) {
            xx.append(array[0]);
            return;
        } else if (length == 0) {
            return;
        }
        int variNum = 0;
        int nextK = 0;
        int increase = 0;
        for (int i =0; i<length; i++) {
            if (k<cons[i+1]) {
                variNum = i;
                nextK = k%cons[i];
                increase = k/cons[i];
                break;
            }
        }
        int tmp = array[length-variNum-1];
        array[length-variNum-1] = array[length-variNum-1+increase];
        array[length-variNum-1+increase] = tmp;
        for (int i = 0; i< length-variNum; i++) {
            xx.append(array[i]);
        }
        int[] nestArray = new int[variNum];

        System.arraycopy(array, length-variNum, nestArray, 0, variNum);

        getkIndex(xx, nestArray, nextK, cons);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值