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.
调用上一题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 个排列,上述算法计算了所有排列,耗时太大,不能满足要求。
[1,2,3,…,n] 包含了
另外由
1. “123”
2. “132”
3. “213”
4. “231”
5. “312”
6. “321”可以观察到只有k=1 123;k=2 132
同时满足,第1位为1,即
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;
}
};
leetcode | Permutation Sequence
原文地址:http://blog.csdn.net/quzhongxin/article/details/46275003