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

Leetcode: Permutation Sequence

2014-05-31 18:24 267 查看
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<int> table(n-1, 0);
vector<int> nums(n, 0);
string ret;
int i, c;

if (n == 1) return "1";

table[n-2] = 1;
for (i = n-3; i >= 0; i--) {
table[i] = table[i+1] * (n-1-i);
}

i = 1;
while(i < n) {
c = (k-1) / table[i-1];
k -= c * table[i-1];
c = pickNumber(nums, c+1);
ret.append(1, '0'+c);
++i;
if (k == 0) break;
}

for (i = 0; i < n; i++) {
if (nums[i] == 0) {
ret.append(1, '0'+i+1);
}
}

return ret;
}

private:
int pickNumber(vector<int> &nums, int n) {
int i = 0;
int k = 0;

while (i < nums.size()) {
if (nums[i] == 0) {
++k;
if (k == n) {
nums[i] = 1;
return i+1;
}
}
++i;
}

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