zoukankan      html  css  js  c++  java
  • [LeetCode]Permutation Sequence

    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.

    这个字符串的规律就是由小到大的数字序列,第k个字符串就是第k大的数字序列字符串,那么暴力遍历是可行的,但是太慢。

    还有个方法就是康托展开,时间复杂度O(n),空间复杂度O(1)。

     1 class Solution {
     2 public:
     3     string getPermutation(int n, int k) {
     4         vector<int> numbers;
     5         for(int i=1;i<=n;i++)
     6         {
     7             numbers.push_back(i);
     8         }
     9         vector<int> result;
    10         int b=k-1;
    11         for(int i=n-1;i>=0;i--)
    12         {
    13             int a=b/(jiecheng(i));
    14             result.push_back(numbers[a]);
    15             numbers.erase(numbers.begin()+a);
    16             if(i!=0)
    17             {
    18                b=b%(jiecheng(i));
    19             }
    20         }
    21         string result_str;
    22         for(int i=0;i<result.size();i++)
    23         {
    24             char ch=result[i]+48;
    25             result_str+=ch;
    26         }
    27         return result_str;
    28     }
    29     int jiecheng(int n)
    30     {
    31         int result=1;
    32         for(int i=1;i<=n;i++)
    33         {
    34             result*=i;
    35         }
    36         return result;
    37     }
    38 };
  • 相关阅读:
    SQL第3课:具有约束的查询(第2部分)
    SQL第1课:SELECT查询
    idea快捷键
    Vue基础
    分布式基础
    数据结构-线性表
    常用算法
    数据结构-概述
    Django使用Jinja2模板引擎
    宿主机nginx使用容器php-fpm处理php请求
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4732527.html
Copyright © 2011-2022 走看看