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

    题解:

    Solution 1 

    class Solution {
    public:
        string getPermutation(int n, int k) {
            string s;
            for(int i = 0; i < n; ++i){
                s += (i + 1) + '0';
            }
            for(int i = 0; i < k - 1; ++i){
                next_permutation(s);
            }
            return s;
        }
        void next_permutation(string &str){
            int n = str.size();
            for(int i = n - 2; i >= 0; --i){
                if(str[i] >= str[i + 1]) continue;
                int j = n - 1;
                for(; j > i; --j) {
                    if(str[j] > str[i]) break;       
                }
                swap(str[i], str[j]);
                reverse(str.begin() + i + 1, str.end());
                return;
            }
            reverse(str.begin(), str.end());
        }
    };

    Solution 2 

    class Solution {
    public:
        string getPermutation(int n, int k) {
            string res;
            if(n <= 0 || k <= 0){
                return res;
            }
            string num = "123456789";
            vector<int> f(n, 1);
            for(int i = 1; i < n; ++i){
                f[i] = f[i - 1] * i;
            }
            --k;
            for(int i = n; i > 0; --i){
                int j = k / f[i - 1];
                k %= f[i - 1];
                res.push_back(num[j]);
                num.erase(j, 1);
            }
            return res;
        }
    };

    康托编码

    Solution 3

    class Solution {
    public:
        string getPermutation(int n, int k) {
            string s = "123456789", str;
            int factorial = 1;
            for(int i = 1; i < n; ++i){
                factorial *= i;
            }
            --k;
            for(int i = n; i > 0; --i){
                int index = k / factorial;
                str += s[index];
                s.erase(index, 1);
                k %= factorial;
                factorial /= i - 1 ? i - 1 : 1;
            }
            return str;
        }
    };
  • 相关阅读:
    Shiro【常用的自定义】
    Shiro【重要概念总结】
    Shiro【自定义Realm实战】
    Shiro【内置Realm实操】
    Shiro【快速上手】
    Shiro【初识】
    面向对象【抽象类和接口的区别】
    面向对象【多态中的成员访问特点】
    Kafka2.12-2.5.0在windows环境的安装 启动 通信测试
    CentOS.iso 下载地址收纳整理
  • 原文地址:https://www.cnblogs.com/Atanisi/p/7477303.html
Copyright © 2011-2022 走看看