zoukankan      html  css  js  c++  java
  • 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"

    找出第k排列数,

    思路一:将所有排列数都计算出来放到一个数组中,寻找第k个。该方法超时

    思路二:利用next_perm来计算下一个排列数,寻找k次即可。

    参考代码如下:

    注释里为STL代码

    class Solution {
    public:
        string getPermutation(int n, int k) {
            string str;
            for (int i = 1; i <= n; ++i)
                str += '0' + i;
            while (--k)
            {
                // next_permutation(str.begin(), str.end());
                nextPermutation(str);
            }
            return str;
        }
        
        void nextPermutation(string& nums) {
            if (nums.empty())
                return;
            int n = nums.size();
            int i = 0, j = n-1, k = n-1;
            if (i == j || i > j)
                return;
            while (j > 0)
            {
                if (nums[j] > nums[j-1])
                {
                    i = j - 1;
                    break;
                }
                j--;
            }
            while (k > i)
            {
                if (nums[k] > nums[i])
                {
                    swap(nums[k], nums[i]);
                    break;
                }
                k--;
            }
            reverse(nums.begin() + j, nums.end());
        }
    };
  • 相关阅读:
    【转】揭秘令牌桶
    各空白字符说明
    【转】Python正则表达式指南
    python的urlparse
    【转】HTTP Header 详解
    ElasticSearch(六)底层索引控制
    ElasticeSearch(五)分布式索引架构
    Elasticsearch(四)优化用户体验
    ElasticSearch(三)不仅仅是查询
    ElasticSearch(二) 关于DSL
  • 原文地址:https://www.cnblogs.com/immjc/p/9341714.html
Copyright © 2011-2022 走看看