zoukankan      html  css  js  c++  java
  • 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.

    Note: Given n will be between 1 and 9 inclusive.

    分析:对于n的排列来说,第一个数字出现的区间是第1个到(n-1)!个排列。用 (k - 1) / (n - 1)! 所得到的index就是第一个数字所在的最小序列(12345……n-1)的下标。将最小序列的index位置上的数字删除。

    已经用了(n - 1)!个数字了,那么还剩下k = k - index * (n - 1)!这么多个数。如何确定第二个数字呢?同理,第二个数字出现的区间是之后的1到(n - 2)!个排列。用(k - 1)/ (n - 2)! 所得到的index 就可以确定 第二个数字在 上面已经删除了某些index的最小序列中的位置。

    以此类推。

    运行时间4ms

     1 class Solution {
     2 public:
     3     string getPermutation(int n, int k) {
     4         string result;
     5         vector<int> base;
     6         for(int i = 0; i < n; i++) base.push_back(i + 1);
     7         
     8         for(int j = n - 1; j >= 0; j--){
     9             int index = (k - 1) / factorial(j);
    10             k = k - index * factorial(j);
    11             result += '0' + base[index];
    12             base.erase(base.begin() + index);
    13         }
    14         return result;
    15     }
    16     int factorial(int n){
    17         if(n == 0) return 1;
    18         else return n * factorial(n - 1);
    19     }
    20 };
  • 相关阅读:
    kafka学习笔记:知识点整理
    java操作hbase 增删改查
    json往前台送数据中文乱码
    17年数据结构笔记
    设置MYSQL数据库编码为UTF-8
    c++的 struct和class
    算法之arrays and strings
    对于快速排序的理解
    sql杂记
    Spring搭建练习遇到的坑
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4500826.html
Copyright © 2011-2022 走看看