zoukankan      html  css  js  c++  java
  • 【LeetCode】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 (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.

    提示:

    这道题我一上来使用了backtracking的方法依次构造出排列数,当然结果不出所料的TLE了。实际上,仔细观察这些数字,我们还是不难发现一些规律的。

    假设有四位数字{1, 2, 3, 4},那么他们能够产生的排列数是什么呢?

    • 1 + {2, 3, 4}
    • 2 + {1, 3, 4}
    • 3 + {1, 2, 4}
    • 4 + {1, 2, 3}

    其实就是选定第一位数字后,其他剩下的数字进行排列组合,就能求出以该数字打头的所有排列组合。想必已经能发现一些规律了,我们干脆再举一个具体的例子,比如我们现在想要找第14个数,那么由于14 = 6 + 6 + 2。因此第一个数打头的是3,然后再求{1, 2, 4}中第二个排列组合数,答案是"142"。所以最终答案就是"3142"啦。

    这里有一些问题是需要我们注意的:

    • 构造排列数从最高位开始,当选出一个数字后,就应当把这个数字erase掉,防止后面又出现;
    • 我们所要求的第k个数需要在每次循环中减去对应的值;
    • 注意程序中的数组是从0开始的,但题目的输入是从1开始计数的。

    代码:

    class Solution {
    public:
        string getPermutation(int n, int k) {
            vector<int> permutation(n + 1, 1);
            for (int i = 1; i <= n; ++i) {
                permutation[i] = permutation[i - 1] * i;
            }
            vector<char> digits = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            int num = n - 1;
            string res;
            while (num) {
                int t = (k - 1) / (permutation[num--]);
                k = k - t * permutation[num + 1];
                res.push_back(digits[t]);
                digits.erase(digits.begin() + t);
            }
            res.push_back(digits[k - 1]);
            return res;
        }
    };
  • 相关阅读:
    Modelsim中观测代码覆盖率
    Allegro中Thermal relief Pad 和Anti Pad
    时序逻辑中阻塞赋值引起的仿真问题
    如何提高FPGA工作频率(转载)
    `include在Verilog中的应用
    forever
    wxpython 应用 使用 google gauth 认证
    sql to sqlalchemy 转换
    django 简易博客开发 5 markdown支持、代码高亮、gravatar头像服务
    simpletodo: 一个简易的 todo 程序 django版
  • 原文地址:https://www.cnblogs.com/jdneo/p/5305212.html
Copyright © 2011-2022 走看看