• LeetCode "Permutation Sequence"


    1A! This is actually a basic question in Combinatorics: if at digit[k] = n, it contributes (k-1)! * n to the targeted index.

    class Solution {
    public:
        unsigned long long nPrime(unsigned n)
        {
            if (n == 1) return 1;
            return n * nPrime(n - 1);
        }
        string getPermutation(int n, int k) {
            if (n == 1) return "1";
            unsigned long long nbase = nPrime(n - 1);
            k--;
            
            //    Record counts
            vector<int> inx;
            for (int i = n; i >= 1; i--)
            {
                int currInx = k / nbase;
                inx.push_back(currInx);
    
                k -= nbase * currInx;
                if(nbase > 1) nbase /= (i - 1);
            }
    
            //    Recover digits        
            string ret;
            unordered_set<int> mark;
            for (int i = 0; i < inx.size(); i++)
            {
                int currInx = inx[i];
                int k;
                for (k = 0; k < 9 && currInx >= 0; k ++)
                {
                    if (mark.find(k) == mark.end()) currInx--;
                }
                ret += '0' + k;
                mark.insert(k - 1);
            }
            return ret;
        }
    };
  • 相关阅读:
    centos崩溃后如何修复
    乘法是啥
    接上篇—用spring注入DBbean,并使用maven管理
    技术产生价值
    技术?
    世界的本质是啥呢
    java-web 登陆功能
    对java的理解
    数学的历史
    使用jmeter测试接口
  • 原文地址:https://www.cnblogs.com/tonix/p/3921868.html
Copyright © 2020-2023  润新知