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

[LeetCode]Permutation Sequence

2015-08-12 22:54 323 查看

题目

Number: 60

Difficulty: Medium

Tags: Backtracking, Math

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.

题解

求解
n
个数的全排列中第
k
个排列。

对于
n
位数的全排列,如果第一个数字是
1
的排列有
(n-1)!
个,同样可得出每一位数字。

代码

[code]string getPermutation(int n, int k) {
    string res(n, '1');
    vector<int> l;
    for(int i = 0; i < n; i ++){
        l.push_back(i);
        res[i] = '1' + i;
    }
    if(k == 1)
        return res;
    vector<int> fac(n, 1);
    for(int i = n - 3; i >= 0; i--){
        fac[i] = fac[i + 1] * (n -i - 1);
    }
    k = k - 1;
    for(int i = 0; i < n; i++){
        int select = k / fac[i];
        k %= fac[i];
        res[i] = l[select ] + '1';
        remove(l.begin(), l.end(), l[select]);
    }
    return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: