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

Leetcode 60. Permutation Sequence

2018-02-03 08:28 761 查看
原题:

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位上一个数字出现的次数是(n-1)!次。根据这个特性,我们从高位开始取数字,知道所有的数字被取出。

代码:
string getPermutation(int n, int k) {
string num = "123456789", res = "";
vector<int> func(n, 1);
for(int i = 1; i < n;i++){
func[i] = func[i-1] * i;
}

--k;
for(int i=n;i > 0; i--){
int index = k/func[i-1];
k %= func[i-1];

res += num[index];
num.erase(index, 1);
}

return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C Leetcode