Permutation Sequence [LeetCode]
2013-11-14 16:27
519 查看
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.
Solutions: Caculates the index of the first number by idx = (k -1) / (n-1)! , and the new k and new n, then goes to next round.
[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.
Solutions: Caculates the index of the first number by idx = (k -1) / (n-1)! , and the new k and new n, then goes to next round.
string getPermutation(int n, int k) { vector<int> nums; vector<int> factors(1,1); for(int i = 1; i <= n; i++){ nums.push_back(i); factors.push_back(factors[i - 1] * i); } string ret; while(k > 0 && nums.size() > 0) { int idx = (k -1) / factors[n -1]; ret.push_back(nums[idx] + 48); nums.erase(nums.begin() + idx); k = k - idx * factors[n - 1]; n --; } return ret; }
相关文章推荐
- [LeetCode]Trapping Rain Water
- LeetCode(13) RomanToInteger
- Recover Binary Search Tree -- LeetCode
- leetcode 之 Two Sum 解题思路
- [LeetCode]Sort List
- leetcode[125] Valid Palindrome
- 83. Remove Duplicates from Sorted List Leetcode Python
- leetcode_36_validsudoku
- leetcode 第89题 Gray Code
- [LeetCode][Java] Jump Game
- Leetcode: Happy Number
- LeetCode-Valid Anagram
- LeetCode Longest Substring Without Repeating Characters
- [LeetCode 088] Merge Sorted Array
- leetcode 2 Add Two Numbers
- Leetcode 326. Power of Three
- LeetCode-233.Number of Digit One
- (LeetCode)Linked List Cycle --- 判断循环链表
- [leetcode] 438. Find All Anagrams in a String 解题报告
- Leetcode 90. Subsets II