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;
}
};