码迷,mamicode.com
首页 > 其他好文 > 详细

60. Permutation Sequence

时间:2016-05-09 06:53:14      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

    /*
     * 60. Permutation Sequence 
     * 2016-5-8 by Mingyang 纯数学问题
     * 虽然看起来思路很简单,但是实现起来却很巧妙。
     * 首先我们都很清除,permutation完成再来看第k个是可以的,但也是不高效的
     * 那我们现在首先通过k来除以base来确定第一个数字,再利用剩下的recursive来做的话
     * 如何去除掉刚刚我们加了的那个数字呢?
     * 我没有想起来,网上的一个大神用了一个ArrayList来表示所有的n,直接remove掉就好了
     */
    public String getPermutation(int n, int k) {
        k--;// to transfer it as begin from 0 rather than 1
        List<Integer> numList = new ArrayList<Integer>();
        for (int i = 1; i <= n; i++)
            numList.add(i);
        int factorial = 1;
        for (int i = 2; i < n; i++)
            factorial *= i;
        StringBuilder res = new StringBuilder();
        int times = n - 1;
        while (times >= 0) {
            int indexInList = k / factorial; // 决定落在第几个区间
            res.append(numList.get(indexInList));
            numList.remove(indexInList);
            k = k % factorial;// 这道题目的说明很清晰,就是k与factorial将决定最终的k在哪里,
    //那么我每次循环就是不断地更新两个值的变化,那么k在下一个range里面的排位需要模现在的factorial
            if (times != 0)
                factorial = factorial / times;// new (n-1)!
        // 当然,下一个range就更小一轮了,除以times就好了
            times--;
        }
        return res.toString();
    }

 

60. Permutation Sequence

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5472484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!