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

leetcode:Permutation Sequence

2016-03-13 20:39 281 查看
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.

Subscribe to see which companies asked this question
class Solution {

private:
unsigned int hashTable[9];

unsigned int getPai(int n) {

if (n == 0)
return 1;

if (hashTable
!= 0)
return hashTable
;

if (n==1)
{
hashTable[1] = 1;
return 1;
}

unsigned int ret = n*getPai(n-1);
hashTable
= ret;

return ret;
}

string getPermutationHelper(vector<char> &model, int k) {

int n = model.size();
if (n == 0)
return "";

int numIdx = (k-1) / getPai(n-1); // (k-1) 这里很关键
int remain = k - numIdx*getPai(n-1); // remain = k-numIdx*getPai(n-1)也很关键

char targetChar = model[numIdx];
vector<char> next;

for (int i=0; i<model.size(); i++)
{
if (i != numIdx)
next.push_back(model[i]);
}

return model[numIdx] + getPermutationHelper(next, remain);
}

public:
string getPermutation(int n, int k) {

vector<char> model(n);
for (int i=1; i<=n; i++)
{
model[i-1] = i+'0';
}

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