LeetCode||60. Permutation Sequence
来源:互联网 发布:视频剪辑制作软件电脑 编辑:程序博客网 时间:2024/06/06 16:40
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.
本来想枚举的,9!数量不是巨大,还是怕超时,找了个比较有技术含量的计算方式。
计算第k个Permutation。假设n = 6,k = 400
先计算第一位,
第一位为6,那么它最少也是第5! * 5 + 1个排列,这是因为第一位为1/2/3/4/5时,都有5!个排列,因此第一位为6时,至少是第5! * 5 + 1个排列(这个排列为612345)。
5! * 5 + 1 = 601 > k,所以第一位不可能是6.
一个一个地枚举,直到第一位为4时才行,这时,4xxxxx至少为第5! * 3 + 1 = 361个排列。
然后计算第二位,与计算第一位时的区别在于,46xxxx至少为第4! * 4 + 1 = 97个排列,这是因为比6小的只有5/3/2/1了。
最后可以计算出第二位为2。
最终得出第400个排列为425361。
class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ res = '' k -= 1 fac = 1 for i in range(1,n): fac *= i num = [1, 2, 3, 4, 5, 6, 7, 8, 9] for i in reversed(range(n)): curr = num[k/fac] res += str(curr) num.remove(curr) if i != 0: k %= fac fac /= i 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
- 软键盘弹出影响webapp中固定定位的问题
- Lamda Expressions
- java 项目连接mysql 数据库
- $.extend()和$.fn.extend()
- leetcode 40. Combination Sum II
- LeetCode||60. Permutation Sequence
- 1+2+3+4+5+6+7+8+9+10
- Android--Glide图片加载框架的基本使用与介绍
- Java实现大数据简单运算
- Cookie保存用户访问网页的时间(七)
- 虚拟机黑屏,日志文件vmware显示DictionaryLoad: Cannot open file "C:\Users\weihy\AppData\Roaming\VMware\config.ini
- MySQL 聚簇索引和聚簇索引(二级索引)
- Java基础02 方法与数据成员
- 数据结构第四次上机 第四章之链串