码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Permutation Sequence"

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

标签:style   blog   color   io   for   ar   div   amp   

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"

标签:style   blog   color   io   for   ar   div   amp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!