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 (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.

    分析: 这道题目看似可以采用全排列的方式得到所有组合,之后排序筛选出第k个大小的组合,但是会超出时间,仔细考虑题目中只要求第k个大小的组合,假设n=4, k=7; 4个数共有4x3x2x1 24个组合,考虑排在第k=7的组合的第一个数,应该是2, 因为第一个数可能为1,2,3,4中的任何一个,每一个情况都有3x2x1 6种情况, 所以向上取整7/6 为2, 这样第一个数就可以确定了,第二个数的情况排除第一个数, 考虑1,3,4 中第 k-(k/6) 中第一个数就可以了,依次类推

    class Solution {
    public:
        int factorial(int n){
            if(n==0 || n==1)
                return 1;
            int res=1;
            for(int i =2; i<=n;i++)
                res*=i;
            return res;
        }
        char helper(string& s, int& k){
            int n = factorial(s.size()-1);
            int index = (k-1)/n;
            char res = s[index];
            s.erase(index,1);
            k -= n*index;
            return res;
        }
        string getPermutation(int n, int k) {
            string str = string("123456789").substr(0,n);
            string res(n,' ');
            for(int i=0; i<n; i++)
                res[i] =helper(str,k);
            return res;
        }
    };
  • 相关阅读:
    2019年计划书单
    redis 分布式锁实现
    filter-grok,dissect匹配数据
    nohup-长期运行进程
    filter
    kill
    watch
    free
    jar
    tree
  • 原文地址:https://www.cnblogs.com/willwu/p/6234946.html
Copyright © 2011-2022 走看看