zoukankan      html  css  js  c++  java
  • 【LeetCode】60. Permutation Sequence

    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.

    我的方法从高位到低位逐位确定数字。

    以图例n=3进行说明:

    构建数组v={1,2,3}

    确定最高位:

    ind=(k-1)/2

    注:分母2是指每个最高位持续的排列数。由于除了最高位之外还有n-1=2位,一共可以出现2!种排列。

    ind指的是所求的第k个排列会落在哪一个最高位的覆盖范围内。

    k==1,2时,ind==0,最高位为v[ind]==1

    k==3,4时,ind==1,最高位为v[ind]==2

    k==5,6时,ind==2,最高位为v[ind]==3

    其余数位如上思路逐位确定。

    注意:

    1、k的更新。

    2、vector<int> v的更新。

    class Solution {
    public:
        string getPermutation(int n, int k) {
            string ret;
            vector<int> v(n);
            for(int i = 0; i < n; i ++)
                v[i] = i+1;
            while(n)
            {
                int ind = (k-1) / fac(n-1);
                ret += (v[ind]+'0');
                k -= ind * fac(n-1);
                for(int i = ind+1; i < n; i ++)
                    v[i-1] = v[i];
                v.pop_back();
                n --;
            }
            return ret;
        }
        int fac(int n)
        {//9! will not overflow
            int ret = 1;
            while(n)
            {
                ret *= n;
                n --;
            }
            return ret;
        }
    };

  • 相关阅读:
    jsp 页面获取当前路径
    html5 页面音频
    微信关于网页授权access_token和普通access_token的区别
    Texlive source
    vscode 快捷键
    vscode setting
    vscode extension 插件管理
    what
    linux manual
    java tool type
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4156188.html
Copyright © 2011-2022 走看看