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):
    "123"
    "132"
    "213"
    "231"
    "312"
    "321"
    Given n and k, return the kth permutation sequence.
    Note: Given n will be between 1 and 9 inclusive.

    我们以n = 4,k = 17为例,数组src = [1,2,3,...,n]。 第17个排列的第一个数是什么呢:我们知道以某个数固定开头的排列个数 = (n-1)! = 3! = 6, 即以1和2开头的排列总共6*2 = 12个,12 < 17, 因此第17个排列的第一个数不可能是1或者2,6*3 > 17, 因此第17个排列的第一个数是3。到第2位时,以某个数固定开头的排列个数即为(n-2)!,即以1和2和3的排列共2!*3=6,12+6>17,因此只能选到2,2!*2=4,12+4<17,因此第三位即为1,以此类推,得到答案,代码如下:

     1 #include<iostream>
     2 #include<vector>
     3 #include<string>
     4 using namespace std;
     5 int factorial(int num)
     6 {
     7      int value = 1;
     8      for(int j = 2;j <= num;j++)
     9      {
    10           value *= j;
    11      }
    12      return value;
    13 }
    14 string permutationSequence(int n,int k)
    15 {
    16      string str = "123456789";
    17      string getStr = str.substr(0,n);
    18      string res(n,' ');
    19      
    20      for(int i = 0;i < n;i++)
    21      {
    22           int temp = factorial(n-1-i);
    23           int index = (k-1)/temp;
    24           res[i] = getStr[index];
    25           
    26           getStr.erase(index,1);
    27           k-=index*temp;
    28   
    29      }
    30 
    31      return res;
    32 }
    33 
    34 int main()
    35 {
    36      
    37      string result;
    38      result = permutationSequence(4,15);
    39      cout << "The result is:" << result << "
    ";
    40 }

     

  • 相关阅读:
    mysql同步 小问题
    通过 XtraBackup 实现不停机不锁表搭建主从同步
    grep -A -B选项详解和mysqlbinlog
    MySQL存储过程中的3种循环
    mysql利用存储过程批量插入数据
    React routerV4 笔记
    数据结构算法基础定义
    网站性能优化
    去重除了indexOf的其他方法(使用对象Key的方法)及统计重复次数
    立即执行函数的两种写法及闭包
  • 原文地址:https://www.cnblogs.com/cocos2014/p/4397909.html
Copyright © 2011-2022 走看看