zoukankan      html  css  js  c++  java
  • 【leetcode】 Permutation Sequence (middle)

    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.

    思路:给定序号找排列的字符串,肯定不用一个一个求,根据序号来判断每一位上的数字。用一个向量存储 0~n-1的阶乘,用另一个向量vec从小到大存1~n数字, 求第k位的话,我们用k-1(转为从0开始), 除以(n-1)!  其整数部分就是该位数字在vec的序号。之后在vec中删掉该数字,k2 %= (n-1)! 以此类推

    class Solution {
    public:
        string getPermutation(int n, int k) {
            vector<int> factorial(n, 1);
            vector<int> vec(n, 1);
            string ans;
            for(int i = 1; i < n; i++)
            {
                factorial[i] = factorial[i - 1] * i;
                vec[i] = i + 1;
            }
            if(k > factorial[n - 1] * n)
                return ans;
    
            int k2 = k - 1;
            for(int i = n - 1; i >= 0; i--)
            {
                int cur = k2 / factorial[i];
                char c[2];
                c[0] = '0' + vec[cur];
                c[1] = '';
                ans.append(c);
                vec.erase(vec.begin() + cur);
                k2 = k2 % factorial[i];
            }
            return ans;
        }
    };
  • 相关阅读:
    Nodejs
    webpack与gulp的区别
    gulpjs
    Commonjs、AMD、CMD
    建造者模式
    工厂模式
    设计模式分类
    python的接口
    Python代码教你批量将PDF转为Word
    什么是“堆”,"栈","堆栈","队列",它们的区别?
  • 原文地址:https://www.cnblogs.com/dplearning/p/4204608.html
Copyright © 2011-2022 走看看