题目描述:
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.
解题思路:
这题借用了Next Permutation的思路,只是用k记录循环次数而已。
代码:
class Solution { public: string getPermutation(int n, int k) { string nums = ""; for (int i = 1; i <= n; i++) nums += i + '0'; int index = 0; for (int j = 1; j < k; j++) { index = nums.size() - 1; while (nums[index] <= nums[index - 1] && index>1) index--; for (int i = nums.size() - 1; i >= index - 1; i--) { if (nums[i] > nums[index - 1]) { swap(nums[index - 1], nums[i]); break; } } reverse(nums.begin() + index, nums.end()); } return nums; } };