[LeetCode] 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 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.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3 Output: "213"
Example 2:
Input: n = 4, k = 9 Output: "2314"
找出第k排列数,
思路一:将所有排列数都计算出来放到一个数组中,寻找第k个。该方法超时
思路二:利用next_perm来计算下一个排列数,寻找k次即可。
参考代码如下:
注释里为STL代码
class Solution { public: string getPermutation(int n, int k) { string str; for (int i = 1; i <= n; ++i) str += '0' + i; while (--k) { // next_permutation(str.begin(), str.end()); nextPermutation(str); } return str; } void nextPermutation(string& nums) { if (nums.empty()) return; int n = nums.size(); int i = 0, j = n-1, k = n-1; if (i == j || i > j) return; while (j > 0) { if (nums[j] > nums[j-1]) { i = j - 1; break; } j--; } while (k > i) { if (nums[k] > nums[i]) { swap(nums[k], nums[i]); break; } k--; } reverse(nums.begin() + j, nums.end()); } };