zoukankan      html  css  js  c++  java
  • [LeetCode] 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基础』第3节:变量和基础数据类型
    Python全栈之路(目录)
    前端
    Python十讲
    Ashampoo Driver Updater
    druid 连接池的配置
    webService 入门级
    pom
    pom----Maven内置属性及使用
    webservice 总结
  • 原文地址:https://www.cnblogs.com/immjc/p/9341717.html
Copyright © 2011-2022 走看看