60. Permutation Sequence
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)
{
if (n == 1)
return "1";
vector<int> m1;
string result;
int p = 1; //记录一共有多少种
for(int i=1;i<=n;i++)
{
p = p * i;
m1.push_back(i);
}
for(int i = n; i > 0; i--)
{
p = p / i; //以马上找到的这一位后面有多少种情况
result = result + char(m1[(k-1)/p] + 48);
m1.erase(m1.begin() + (k - 1) / p); //把插入过的删除
k = k - (k-1)/p * p;
}
return result;
}
};
本文介绍了一种求解第K个排列序列的有效算法。通过递减范围的方式,该算法能够在给定整数n和k的情况下,快速找到由1到n组成的唯一排列中的第k个序列。
220

被折叠的 条评论
为什么被折叠?



