Leetcode 60. Permutation Sequence
来源:互联网 发布:mac怎么上传淘宝助理 编辑:程序博客网 时间:2024/06/05 05:18
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.
s思路:
1. 把所有1-9的排列数预先计算出来,即:{0,1,2,6,24,120,720,5040,40320,362880}。例如:n=4时:
1,2,3,41,2,4,31,3,2,41,3,4,21,4,2,31,4,3,22,1,3,42,1,4,32,3,1,42,3,4,12,4,1,32,4,3,13,1,2,43,1,4,2...
s上面列举了前14个排列。可以看出规律,第一位为1的有6个,为2、3、4的都有6个,为什么是6?因为第三个数的排列数刚好是6。所以,先用k/6得到第一位的数,然后k=k%6,在用k/2得到第二位数,然后更新k=k%2;最后k/1得到第三位数,剩下的数就是第四位数
class Solution {public: string getPermutation(int n, int k) { // //vector<int> fact{0,1,2,6,24,120,720,5040,40320,362880}; int fact[10]={0,1,2,6,24,120,720,5040,40320,362880};//优化:用array比vector速度快!! //这样不好set<int> ss{0,1,2,3,4,5,6,7,8,9};// string num="123456789";//简洁的存储数据,不用搞成set<int>,再取出数to_string(),就太不简洁 string res=""; k--; n--; while(n>0){ int idx=k/fact[n]; res+=num[idx]; k=k%fact[n]; num.erase(idx,1);//idx开头长度为1 n--; } res+=num[0]; return res; }};
0 0
- 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
- [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
- 剑指offer——判断是不是栈的弹出序列
- Direct2D简介(原ZDD)
- 彻底掌握Android多分包技术MultiDex-用Ant和Gradle分别构建(一)
- 第一篇 安装和运行windows docker
- 数列有序! (sdut oj)
- Leetcode 60. Permutation Sequence
- javascript异步上传压缩图片并立即显示图片
- 矩阵输出 (sdut oj)
- 数据库乐观锁
- 对nginx上传文件的第三方实现nginx-upload-module的修改
- require.js介绍以及用法
- 排序问题 (sdut oj)
- pandas常用的数据分析函数(一)
- 微信小程序开发——map地图组件,定位,并手动修改位置偏差。