zoukankan      html  css  js  c++  java
  • LeetCode60 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.(Medium)

    分析:

    如果采用next_permutation一个一个找的话会超时,所以考虑直接构造的方式。

    k / (n-1)! 表示了当前这一位应该取剩下的备选元素中的第几个元素,然后k 减去这一位布置后占据了多少个在k之前的序列,并且n--, 以此递推下去,可以得到结果。

    代码:

     1 class Solution {
     2 private:
     3     int fact(int n) {
     4         int result = 1;
     5         for (int i = 1; i <= n; ++i) {
     6             result *= i;
     7         }
     8         return result;
     9     }
    10 public:
    11     string getPermutation(int n, int k) {
    12         string result;
    13         vector<int> init(n);
    14         for (int i = 0; i < n; ++i) {
    15             init[i] = i + 1;
    16         }
    17         int i = k - 1, count = n;
    18                    
    19         while (i >= 0 && count > 0) {
    20             int temp = i / fact(count - 1);
    21             result += ('0' + init[temp]);
    22             i -= ( temp * fact(count - 1));
    23             init.erase(init.begin() + temp);
    24             count--;
    25         }
    26         return result;
    27     }
    28 };
     
  • 相关阅读:
    MySQL
    权限(二)
    权限(一)
    化栈为队
    栈的最小值
    实现简易版react中createElement和render方法
    12.整数转罗马数字
    call,apply,bind的理解
    8. 字符串转换整数 (atoi)
    172.阶乘后的0
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5898097.html
Copyright © 2011-2022 走看看