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

60. Permutation Sequence

2016-03-11 23:43 453 查看
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.

string getPermutation(int n, int k) {
int total=1, idx, i;
vector<char> nums;
for(i = 1; i <= n; i++)
{
nums.push_back(i+'0');
total *= i;
}
if(k>total || k<1)
return "";
string s;
s.resize(n);
i = 0;
while(n)
{
total /= n;
idx = (k-1) / total;
s[i++] = nums[idx];
nums.erase(nums.begin()+idx);
k = (k-1) % total +1; //can also be k -= group * idx
n--;
}
return s;
}


// Construct the k-th permutation with a list of n numbers
// Idea: group all permutations according to their first number (so n groups, each of
// (n-1)! numbers), find the group where the k-th permutation belongs, remove the common
// first number from the list and append it to the resulting string, and iteratively
// construct the (((k-1)%(n-1)!)+1)-th permutation with the remaining n-1 numbers
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: