leetcode Permutation Sequence
2013-12-03 20:26
465 查看
Permutation Sequence
Total Accepted: 1819 TotalSubmissions: 9060My Submissions
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.
Discuss
Three problems:
1. overly dependent on next_permutation, TLE
2. --k. If k%a! == b, so the bth character should be brought forward from the rear a elements.
3. If the length is n, n - 1 adjustments are enough. So i = n instead of n - 1
for (i = n - 1; i >= 1; --i) {
class Solution { public: int factorial[10]; string getPermutation(int n, int k) { string res = ""; int i, j, tmp; vector<int> pos; factorial[0] = 1; for (i = 1; i <= n; ++i) { factorial[i] = factorial[i - 1] * i; res.push_back('0' + i); } --k; for (i = n - 1; i >= 1; --i) { pos.push_back(k / factorial[i]); k = k % factorial[i]; } for (i = 0; i < pos.size(); ++i) { tmp = res[i + pos[i]]; for (j = pos[i]; j >= 1; --j) res[i + j] = res[i + j - 1]; res[i] = tmp; } return res; } };
Give a WA code here, find the bug:
class Solution { public: string getPermutation(int n, int k) { vector<int> factorial(n, 1); string res(n, '1'); for (int i = 1; i < n; ++i) { factorial[i] = factorial[i-1]*i; res[i] += i - 1; } --k; for (int i = 0; i < n; ++i) { int tmp = k / factorial[n - 1 - i]; char ch = res[i + tmp]; for (int j = tmp + i; j > i; --j) res[j] = res[j - 1]; res[i] = ch; k = k % factorial[n - 1 - i]; } return res; } };
Another AC version:
class Solution { public: string getPermutation(int n, int k) { vector<int> factorial(n, 1); string res(n, '1'); for (int i = 1; i < n; ++i) { factorial[i] = factorial[i-1]*i; res[i] += i; } --k; for (int i = 0; i < n; ++i) { int tmp = k / factorial[n - 1 - i]; char ch = res[i + tmp]; for (int j = tmp + i; j > i; --j) res[j] = res[j - 1]; res[i] = ch; k = k % factorial[n - 1 - i]; } return res; } };
相关文章推荐
- #leetcode#Permutation Sequence
- LeetCode(Permutation Sequence)输出全排列中第k个排列
- LeetCode 60 Permutation Sequence
- LeetCode——Permutation Sequence
- [LeetCode]题解(python):060-Permutation Sequence
- LeetCode Permutation Sequence
- Permutation Sequence -- leetcode
- LeetCode: Permutation Sequence [059]
- LeetCode 93 Permutation Sequence
- LeetCode刷题笔录Permutation Sequence
- leetcode做题总结,题目Permutation Sequence 2012/03/27
- LeetCode解题报告—— Jump Game & Merge Intervals & Permutation Sequence
- Leetcode--Permutation Sequence
- [LeetCode] Permutation Sequence
- LeetCode:Permutation Sequence
- LeetCode Permutation Sequence
- Leetcode: Permutation Sequence
- LeetCode(60) Permutation Sequence
- LeetCode Permutation Sequence
- [LeetCode] Permutation Sequence