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 };
  • 相关阅读:
    【题解】小Z的袜子
    浅谈最小生成树
    【题解】钻石收藏家
    浅谈线段树
    浅谈拓扑排序
    浅谈树的直径和树的重心
    浅谈求逆序对
    浅谈欧拉回路
    浅谈离散化
    浅谈高斯消元
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4732527.html
Copyright © 2011-2022 走看看