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());
        }
    };
  • 相关阅读:
    什么是ROR
    Struts2中使用Session的两种方法
    js的时间操作方法
    产生4位包含大小字母与数字的验证码
    Java关键字this、super使用总结
    java 反射的实例
    Java语言中定义常量注意事项
    java 静态方法和实例方法的区别
    多线程的例子
    java 中的内省机制
  • 原文地址:https://www.cnblogs.com/immjc/p/9341714.html
Copyright © 2011-2022 走看看