题目链接
Permutation Sequence - LeetCode
注意点
- n >= 1 && n <= 9
- k >= 1 && k <= n!
解法
解法一:Next Permutation - LeetCode用这道题的函数,生成第n个序列,再转成字符串。效率不高
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size(),i = n-2,j = n-1;
while(i >= 0 && nums[i] >= nums[i+1]) i--;
//cout << i;
if(i >= 0)
{
while(nums[j] <= nums[i]) j--;
swap(nums[i],nums[j]);
}
reverse(nums.begin()+i+1,nums.end());
}
string getPermutation(int n, int k) {
string ret ="";
vector<int> nums;
for(int i = 0;i < n;i++)
{
nums.push_back(i+1);
}
while(k > 1)
{
k--;
nextPermutation(nums);
}
for(int i = 0;i <n ;i++)
{
ret += to_string(nums[i]);
}
return ret;
}
};
解法二:参考Grandyang的博客
小结
- 全排列问题的变种