zoukankan      html  css  js  c++  java
  • 060 Permutation Sequence 排列序列

    给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
    按大小顺序列出所有排列情况,并一一标记,
    可得到如下序列 (例如,  n = 3):
       1."123"
       2. "132"
       3. "213"
       4. "231"
       5. "312"
       6. "321"
    给定 n 和 k,返回第 k 个排列序列。
    注意:n 介于1到9之间(包括9)。
    详见:https://leetcode.com/problems/permutation-sequence/description/

    Java实现:

    在数列 1,2,3,... , n构建的全排列中,返回第k个排列。
    对于n个数可以有n!种排列;那么n-1个数就有(n-1)!种排列。
    那么对于n位数来说,如果除去最高位不看,后面的n-1位就有 (n-1)!种排列。
    所以,还是对于n位数来说,每一个不同的最高位数,后面可以拼接(n-1)!种排列。
    所以可以看成是按照每组(n-1)!个这样分组。
    利用k/(n-1)!可以取得最高位在数列中的index。这样第k个排列的最高位就能从数列中的index位取得,此时还要把这个数从数列中删除。
    然后,新的k就可以有k%(n-1)!获得。循环n次即可。同时,为了可以跟数组坐标对其,令k先--。

    class Solution {
        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 fac = 1;    
            for(int i = 2; i < n; i++) { 
                fac *= i;    
            }
            
            StringBuilder res = new StringBuilder();
            int times = n-1;
            while(times>=0){
                int indexInList = k/fac;
                res.append(numList.get(indexInList));  
                numList.remove(indexInList);  
                
                k = k%fac;//new k for next turn
                if(times!=0){
                    fac = fac/times;//new (n-1)!
                }
                times--;
            }
            
            return res.toString();
        }
    }
    

    参考:https://www.cnblogs.com/springfor/p/3896201.html

  • 相关阅读:
    P3478 [POI2008]STA-Station
    P2015 二叉苹果树
    P2014 选课 (树型背包模版)
    求树的每个子树的重心
    求树的直径
    Javascript--防抖与节流
    JavaScript中call和apply的区别
    解决谷歌浏览器“此Flash Player与您的地区不相容,请重新安装Flash”问题(最新版)
    matlab实验代码(总)
    表达式树
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8698696.html
Copyright © 2011-2022 走看看