首页 > 其他 > 详细

LeetCode "Permutation Sequence"

时间:2014-08-19 14:22:04      阅读:209      评论:0      收藏:0      [点我收藏+]

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;
    }
};

LeetCode "Permutation Sequence",布布扣,bubuko.com

LeetCode "Permutation Sequence"

原文:http://www.cnblogs.com/tonix/p/3921868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!