zoukankan      html  css  js  c++  java
  • 60. 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 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.
    • Given k will be between 1 and n! inclusive.

    Example 1:

    Input: n = 3, k = 3
    Output: "213"
    

    Example 2:

    Input: n = 4, k = 9
    Output: "2314"
    
     
    AC code:
    class Solution {
    public:
        string getPermutation(int n, int k) {
            string s(n, 0);
            iota(s.begin(), s.end(), '1');
            vector<int> fact(n, 1);
            string ans(n, 0);
            for (int i = n-3; i >= 0; --i)
                fact[i] = (n - 1 - i) * fact[i+1];
            k = k - 1;
            for (int i = 0; i < n; ++i) {
                int index = k / fact[i];
                k = k % fact[i];
                ans[i] = s[index];
                s.erase(next(s.begin(), index));
            }
            return ans;
        }
    };
    

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Permutation Sequence.

    std::iota

    template <class ForwardIterator, class T>
      void iota (ForwardIterator first, ForwardIterator last, T val);
    Store increasing sequence

    Assigns to every element in the range [first,last) successive values of val, as if incremented with ++val after each element is written.

    The behavior of this function template is equivalent to:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    template <class ForwardIterator, class T>
      void iota (ForwardIterator first, ForwardIterator last, T val)
    {
      while (first!=last) {
        *first = val;
        ++first;
        ++val;
      }
    }
     



    Parameters

    first, last
    Forward iterators to the initial and final positions of the sequence to be written. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
    val
    Initial value for the accumulator.
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    【WPF】给下拉列表ComboBox绑定数据
    【C#】POST请求参数含中文,服务器解析得到乱码
    CentOS下搭建SVN服务器
    MySQL之ALTER
    深入PHP内核之ZVAL
    关于zend_parse_parameters函数
    PHP数组
    shell中比较字符串大小,>和<前需要加上进行转义,否则会输出到文件了
    awk编程基础
    【读书笔记】《Python_Cookbook3》第一章:数据结构和算法
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9820845.html
Copyright © 2011-2022 走看看