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 };
  • 相关阅读:
    字符串匹配之朴素匹配
    XSS的攻击原理
    使用metasploit收集邮箱
    C++实现折半插入排序
    C++插入排序实现
    Java中的NIO
    Hashtable和HashMap区别(面试)
    面向对象:封装(一):构造函数;类的主方法;权限修饰符;对象的创建
    switch多分支语句
    递归和字母数字生成随机数
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4500826.html
Copyright © 2011-2022 走看看