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

    原题链接在这里:https://leetcode.com/problems/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):

    1. "123"
    2. "132"
    3. "213"
    4. "231"
    5. "312"
    6. "321"

    Given n and k, return the kth permutation sequence.

    题解:

    n有n!个permutation, 那么n-1个数就有(n-1)!种排列, n可以分成n组,每组有(n-1)!个数.

    比如n = 6,那么以1,2,3,4,5,6开头的组合必然是各有(n-1)! = 5! = 120中组合, 若K = 299,那么我们先要求解这个k在第几组,k/(n-1)! = 299/120 = 2,也就是说k应该在第3组(注意组号从0开始),组数应该从0开始; 第三组的首个数字应该是3,第一个数字就确定了。

    确定第2个数字的时候,注意这个时候,k应该等于k % 120 = 59,为什么要这么算呢,因为每个组有120个数字,

    而且k在第三组,那么前两组加起来是240,k在第二次循环的时候,应该是从(5-1)!中确定是属于哪个组,其实就是确定k在第三组中是属于哪个位置。

    这个时候59/24 = 2,确定应该是属于第三组,因为在上一步中,3已经用过了,所以这个时候的5个数字是1,2,4,5,6,所以第三组的首个数字是4,依次类推,一直到n个数字全部算完为止。

    k是从1开始的,实际的index是从0开始,所以需要k--.

    Time Complexity: O(n). Space: O(n).

    AC Java:

     1 public class Solution {
     2     public String getPermutation(int n, int k) {
     3         if(n <= 0 || k <= 0){
     4             return "";
     5         }
     6         StringBuilder sb = new StringBuilder();
     7         int [] factorial = new int[n+1];
     8         List<Integer> nums = new ArrayList<Integer>();
     9         
    10         //计算factorial, 并且把1到n都append到nums list后面
    11         factorial[0] = 1;
    12         for(int i = 1; i<=n; i++){
    13             factorial[i] = factorial[i-1] * i;
    14             nums.add(i);
    15         }
    16         
    17         //这里的k是从1开始, 实际的index 是从0开始.
    18         k--;
    19         
    20         for(int i = 1; i<=n; i++){
    21             int index = k/factorial[n-i];
    22             sb.append(nums.get(index));
    23             nums.remove(index);
    24             k = k%factorial[n-i];
    25         }
    26         return sb.toString();
    27     }
    28 }

    跟上Next Permutation.

  • 相关阅读:
    输入输出、基本运算符、流程控制
    Node学习6-fs模块
    Node学习5-events模块
    Node学习4-Buffer模块
    Node学习3-Path模块
    Node学习2-基础知识/HelloWorld/模块调用/global/process
    Node学习1-基本概念
    gulp/bower/less知识
    AngularJS学习1-基础知识
    JavaScript学习-类/原型链/class
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4847742.html
Copyright © 2011-2022 走看看