Leetcode 60. Permutation Sequence
2018-02-03 08:28
761 查看
原题:
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.
解决方法:
比较巧妙的一道题。
根据排列的特性,我们知道在n位上一个数字出现的次数是(n-1)!次。根据这个特性,我们从高位开始取数字,知道所有的数字被取出。
代码:
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.
解决方法:
比较巧妙的一道题。
根据排列的特性,我们知道在n位上一个数字出现的次数是(n-1)!次。根据这个特性,我们从高位开始取数字,知道所有的数字被取出。
代码:
string getPermutation(int n, int k) { string num = "123456789", res = ""; vector<int> func(n, 1); for(int i = 1; i < n;i++){ func[i] = func[i-1] * i; } --k; for(int i=n;i > 0; i--){ int index = k/func[i-1]; k %= func[i-1]; res += num[index]; num.erase(index, 1); } return res; }
相关文章推荐
- [Leetcode] 60. Permutation Sequence 解题报告
- LeetCode --- 60. Permutation Sequence
- LeetCode||60. Permutation Sequence
- LeetCode --- 60. Permutation Sequence
- Leetcode--60. Permutation Sequence
- [leetcode] 60. Permutation Sequence 解题报告
- LeetCode-------60. Permutation Sequence(n的全排列中第K列)
- LeetCode:60. Permutation Sequence
- LeetCode 60. Permutation Sequence 全排列的第k个
- [leetcode] 60. Permutation Sequence
- LEETCODE60. Permutation Sequence
- leetcode No60. Permutation Sequence
- 60. permutation sequence leetcode python
- Leetcode #60. Permutation Sequence 排列组合序列 解题报告
- [LeetCode]60. Permutation Sequence
- leetcode 60. Permutation Sequence
- 【LeetCode】60. Permutation Sequence
- 【一天一道LeetCode】#60. Permutation Sequence.
- leetcode 60. Permutation Sequence
- leetcode 60. Permutation Sequence