• Permutation Sequence


    Question:

    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.

    Solution:

     1 string itoax(int num)
     2 {
     3     stringstream result;
     4 
     5     result<<num;
     6     return result.str();
     7 }
     8 int fac(int n)
     9 {
    10     if(1==n || 0==n)
    11         return 1;
    12     else
    13         return n*fac(n-1);
    14 }
    15 string get_each_char(vector<int> &a,int &k)
    16 {
    17     int n=a.size();
    18     if(1==n) 
    19     {
    20         string b=itoax(a[0]);
    21         a.erase(a.begin(),a.end());
    22         return b;
    23     }
    24     int nn=fac(n-1);
    25     int i=ceil(double(k)/nn);
    26     string b=itoax(a[i-1]);
    27     k=k-nn*(ceil(double(k)/nn)-1);
    28     a.erase(a.begin()+i-1,a.begin()+i);    
    29     return b;
    30 }
    31 class Solution {
    32 public:
    33     string getPermutation(int n, int k) {
    34         string result;
    35     vector<int> a;
    36     for(int i=1;i<=n;i++)
    37         a.push_back(i);
    38     while(!a.empty())
    39     {
    40         string c=get_each_char(a,k);
    41         result +=c;        
    42     }
    43     return result;
    44         
    45     }
    46 };

  • 相关阅读:
    利用scanf函数修改内存中任意位置内容
    TSql
    完整性约束及其违约处理
    实现关机、重启、注销
    建立索引的原则
    我只想安静的大便
    格式化GridView特定的值
    SELECT语句执行顺序解析
    CPU对存储器的读写
    Linux常用97条命令
  • 原文地址:https://www.cnblogs.com/riden/p/4631539.html
Copyright © 2020-2023  润新知