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

Leetcode--60. Permutation Sequence

2017-07-03 11:14 239 查看

题目

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.

思路

假设集合为[1,2,3,4],求出第6个组合。

第6个组合对应的下标为5(下标从0开始),我们首先求出5所对应的lehmer码(lehmer code的解释参考链接1):

5/3! = 0 余5

5/2! = 2 余1

1/1! = 1 余0

0 (lehmer code最后一位总为0)

所以所求lehmer码为0210

当前集合对应的序列为1234

接下来将lehmer码中的每个数字当做当前序列的下标,下标0对应的集合元素为1,当前序列变成234;下标2对应的集合元素为4,当前序列变成23;下标1对应的集合元素为3,当前序列变成2;下标0对应的元素为2

所以所求的组合即为1432

代码

class Solution {
public:
string getPermutation(int n, int k) {
vector<int> jc; ///阶乘表
list<int> li;   ///序列 1234
jc.push_back(1);
int i=1;
for(; i<n; i++) {
jc.push_back(jc[i-1]*i);
li.push_back(i);
}
li.push_back(i);

--k;
string res="";
list<int>::iterator it;
for(int i=n-1; i>0; i--) {
int index = k/jc[i];
it = li.begin();
for(int j=0; j<index; j++) it++;
res += to_string(*it);
li.erase(it);
k = k % jc[i];
}
res += to_string(*li.begin());
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: