[Leetcode] 60. Permutation Sequence 解题报告
来源:互联网 发布:seo网络营销技术 编辑:程序博客网 时间:2024/05/16 09:22
题目:
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.
思路:
1、nextPermutation法:由于我们之前已经实现了nextPermutation,所以只需要先生成一个最小的permutation,然后连续调用k-1次nextPermutation,就可以得到所需要的结果。由于调用nextPermutation的时间复杂度是O(n),所以该思路的时间复杂度是O(n*k),空间复杂度可以做到O(1)(可以直接在string上面做nextPermutation)。此算法仅仅在k <= n的情况下有优势。
2、迭代法:长度为n的字符串的permutation的个数为O(n!),而以任何一个字符开头的permutation共有O((n-1)!)个。通过k值,我们可以首先确定结果字符串中第一个字符;然后更新k值,并且在剩下的字符集合中采取相同的策略确定下一个字符。重复该过程直到n个字符全部被确定。在实现中如果采用vector来表示剩余字符集,则由于每次删除字符集中第k大的字符的时间复杂度高达O(n),所以整个算法的时间复杂度为O(n^2),空间复杂度为O(n)。由于通常情况下 k >> n,所以平均而言思路2比思路1更有优势。(如果有一种数据结构能在最多O(logn)的时间复杂度内完成查找和删除第i大的元素,则该算法的时间复杂度可以进一步降低为O(nlogn),有木有这样的数据结构?)
代码:
class Solution {public: string getPermutation(int n, int k) { string ret; long long factorial = 1; // the indices vector<char> nums(n, '0'); // the letter set for(int i = 0; i < n; ++i) { factorial *= (i == 0 ? 1 : i); nums[i] = '0' + (i + 1); } k--; // convert to 0-based index for(int i = n - 1; i >= 0; --i) { int j = k / factorial; // determine the next letter to be added ret.push_back(nums[j]); nums.erase(nums.begin()+j); k %= factorial; // update the index if(i > 0) factorial /= i; } return ret; }};
- [leetcode] 60. Permutation Sequence 解题报告
- [Leetcode] 60. Permutation Sequence 解题报告
- [leetcode]60. Permutation Sequence@Java解题报告
- Leetcode #60. Permutation Sequence 排列组合序列 解题报告
- 【LeetCode】Next Permutation 解题报告
- LeetCode解题报告--Next Permutation
- [LeetCode] Next Permutation 解题报告
- 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
- LeetCode 60. Permutation Sequence
- leetcode 60. Permutation Sequence
- LeetCode 60. Permutation Sequence
- leetcode:60. Permutation Sequence
- Linux平台总线驱动设备模型
- Yii2 导入导出Excel
- [准确]判断PHP键值数组是否存在,使用empty或isset或array_key_exists
- java多线程concurrent包
- Mac-安装gradle
- [Leetcode] 60. Permutation Sequence 解题报告
- yii2 常用ActiveForm表单样式用法总结
- 火星人永久家园建立在何处?
- python 3.4 error: Microsoft Visual C++ 10.0 is required(Unable to find)亲测解决办法
- Leetcode 3. Longest Substring Without Repeating Characters
- framebuffer_alloc()
- concurrent实现多线程的线程池开发
- 学习任何游戏引擎,编程语言,都应该进来看看
- 在spring中常被忽视的注解 @Primary