您的位置:首页 > 产品设计 > UI/UE

Permutation Sequence -- leetcode

2015-04-01 14:51 260 查看
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):

"123"

"132"

"213"

"231"

"312"

"321"


Given n and k, return the kth permutation sequence.

Note: Given n will be between 1 and 9 inclusive.

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<char> pers(n, '1');
        int fact = n;
        for (int i=1; i<n; i++) {
            fact *= i;
            pers[i] = '1' + i;
        }
        
        k--;
        string ans;
        for (int i=0; i<n; i++) {
            fact /= (n-i);
            const int j = k / fact;
            k %= fact;
            
            ans.push_back(pers[j]);
            pers.erase(pers.begin()+j);
        }
        
        return ans;
    }
};


在leetcode上,实际执行时间为5ms。

基本思路:

参照普通进制的方法,求出每位的权重,从高位到低位利用整除和取余求出每位的值。

区别为,此权重都是阶乘值,不像普通进制,为基数的各次幂。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: