zoukankan      html  css  js  c++  java
  • 60. Permutation Sequence

        /*
         * 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();
        }
  • 相关阅读:
    C语言相关题目6
    C语言相关题目7
    C语言相关题目8
    C语言相关题目9
    哈夫曼编码
    查看linux系统信息命令
    C++基类和派生类的构造函数/析构函数
    C++的const类成员函数
    c++中的static关键字的作用
    为什么二叉树的叶子结点数等于度为2的结点数+1
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5472484.html
Copyright © 2011-2022 走看看