Leetcode: Permutation Sequence
2014-05-31 18:24
267 查看
The set
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
[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.
class Solution { public: string getPermutation(int n, int k) { vector<int> table(n-1, 0); vector<int> nums(n, 0); string ret; int i, c; if (n == 1) return "1"; table[n-2] = 1; for (i = n-3; i >= 0; i--) { table[i] = table[i+1] * (n-1-i); } i = 1; while(i < n) { c = (k-1) / table[i-1]; k -= c * table[i-1]; c = pickNumber(nums, c+1); ret.append(1, '0'+c); ++i; if (k == 0) break; } for (i = 0; i < n; i++) { if (nums[i] == 0) { ret.append(1, '0'+i+1); } } return ret; } private: int pickNumber(vector<int> &nums, int n) { int i = 0; int k = 0; while (i < nums.size()) { if (nums[i] == 0) { ++k; if (k == n) { nums[i] = 1; return i+1; } } ++i; } return nums.size()-1; } };
相关文章推荐
- LeetCode Permutation Sequence
- [leetcode]Permutation Sequence @ Python
- [leetcode-60]Permutation Sequence(C)
- [leetcode-60]Permutation Sequence(C)
- 4.30 leetcode -30 permutation-sequence
- LeetCode Permutation Sequence
- Leetcode_permutation-sequence(c++ and python version)
- LeetCode-Permutation Sequence-计数搜索
- [leetcode]Permutation Sequence
- leetcode Permutation Sequence
- LeetCode(60) Permutation Sequence
- 【Leetcode】【python】Permutation Sequence
- [LeetCode] Next Permutation、Permutations、Permutations II、Permutation Sequence
- LeetCode(60): Permutation Sequence (C++)
- [LeetCode#60]Permutation Sequence
- leetcode之Permutation Sequence
- LeetCode(60) Permutation Sequence
- leetcode Permutation Sequence
- 【leetcode 排列组合问题】Next Permutation | Permutations | Permutations II | Permutation Sequence
- LeetCode Permutation Sequence