Permutation Sequence
来源:互联网 发布:网络屏蔽器软件下载 编辑:程序博客网 时间:2024/05/21 18:48
思路:
方法一:暴力。使用next_permutation(),循环k-1次。但是TLE。
next_permutation前面已经实现过,按如下四步找到当前permutation的下一个permutation:(假设串s)
(1)从右向左找到一个不满足升序的数字,位置记为i;
(2)从右向左找到第一个比s[i]大的数字,位置记为j;
(3)交换s[i]和s[j];
(4)reverse所有i后面的数字;
class Solution {public: string getPermutation(int n, int k) { string s(n, '0'); for(int i = 0; i < n; ++i) { s[i] += i+1; } for(int i = 0; i < k-1; ++i) { next_permutation(s.begin(), s.end()); } return s; }};
方法二:
通过公式直接算出第k个排列。时间复杂度O(N),空间复杂度O(1)。
假设起始串为s:
最终目标串为s’ = a1, a2, a3, … , ak ,(ak表示s’中第k个位置上的数是起始串s中第ak个位置上的数)则该方法直接从a1开始算,直到求出s’的所有位上的数。
假设第1个数固定,则后面还可能有(n-1)!个排列,那么用a1 = k/(n-1)!就可以算出目标串s’的第一个数在起始串s中的位置。(注意起始串第一个数的位置当然是0了)
好,算出目标串s’的第一个数a1后,就可以继续按照这样的方法计算了。
此时,可以去除起始串s中的a1位置上的数,此时更新k,k = k%(n-1)! ,a2 = k/(n-2)!,以此类推。
例如:s = “1234”,n = 4,k = 9。
(这里认为排列“1234”是第0个排列,实际上我们要求的是第8个排列,k= k-1 = 8)
a1 =
去除’2’,s = “134”,更新k,k = 2;
a2 =
去除’3’,s = “14”,更新k,k = 0;
a3 =
去除’1’,s = “4”,直接赋给s’[3]。
所以得出 s’= “2314”。
class Solution {private: int factorial(int n) { //return n! int ans = 1; for(int i = 1; i <= n; ++i) { ans *= i; } return ans; }public: string getPermutation(int n, int k) { string s(n, '0'); string ans; for(int i = 0; i < n; ++i) { s[i] += i+1; } int base = factorial(n-1); --k; for(int i = n - 1; i > 0; --i) { auto iter = next(s.begin(), k/base); ans.push_back(*iter); s.erase(iter); k %= base; base /= i; } ans.push_back(s[0]); return ans; }};
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- Permutation Sequence
- 无向图的邻接矩阵表示和遍历
- Unity实现“海岛奇兵” 水特效
- FastDFS之磁盘恢复过程
- [web安全] Cookie注入
- IOS 使用XIB 自定义View
- Permutation Sequence
- Subversion Native Library not available 解决办法
- oracle数据库管理之表空间
- FastDFS之合并存储缺陷导致数据丢失或错误
- Android和Java的关系和区别
- iOS开发UI篇 -- 0401团购案例-使用xib自定义控件
- 黑马程序员------面向对象02
- 通过AIDL实现挂断电话功能
- 亚马逊资源名称 (ARN) 和 AWS 服务命名空间