Permutation Sequence : https://leetcode.com/problems/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):
1. “123”
2. “132”
3. “213”
4. “231”
5. “312”
6. “321”
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
解析
1. 调用 next Permutation
调用上一题Next Permutation中的函数,逐步计算下一个队列,直到第k个。(暴力枚举)
string getPermutation(int n, int k) {
string result;
vector<int> nums;
for (int i = 1; i <= n; i++)
nums.push_back(i); //初始化第一个排列
for (int j = 1; j < k; j++)
nextPermutation(nums); //计算第k个排列
for (int k = 0; k < n; k++)
result.push_back(nums[k]);
return result;
}
做了很多无用功,因为我们只需得到第 k 个排列,上述算法计算了所有排列,耗时太大,不能满足要求。
2. 数学解法
[1,2,3,…,n] 包含了
n!
种排列,那么以某一个数开头的排列有
(n−1)!
种, 如果
r=k / (n−1)!
,则数字
r
位于第一位,然后从数据集中移出数字
另外由
1. “123”
2. “132”
3. “213”
4. “231”
5. “312”
6. “321”可以观察到只有
k−1
才能保证k=1 123;k=2 132
同时满足,第1位为1,即
(2−1)/2!=0
和
(1−1)/2!=0
class Solution {
public:
string getPermutation(int n, int k) {
string result;
vector<int> set;
for (int i = 1; i <= n; i++)
set.push_back(i);
k--; //k-1后才能应用于整除
int count = factorial(n); // n! 组合数
for (int j = n; j > 0; j--) {
count = count / j; // (j-1)!
int r = k / count;
result.push_back(set[r]+'0');
set.erase(set.begin()+r); //移除set[r],或将r后的元素整体前移一位
k = k % count;
}
return result;
}
private:
int factorial(int n) { //求阶乘
if (n == 0)
return 1;
int result = 1;
while (n) {
result *= n;
n--;
}
return result;
}
};