60. Permutation Sequence(求全排列的第k个排列)
2024-10-21 06:44:59
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.
如果用前面2道题 的递归 非递归 都会超时。
只能用数学的方法计算。
class Solution(object): def getPermutation(self, n, k):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
k = k -1
nums = list(range(1, n + 1))
res = ''
while len(nums)!=0:
ai =int(k/self.fn(n-1))
res += str(nums[ai])
del nums[ai]
k = k % self.fn(n-1)
n = n - 1
return res
def fn(self, n):
res = 1
while n != 0:
res = res * n
n = n - 1
return res
最新文章
- 在Winform界面中实现对多文档窗体的参数传值
- js 模块化历程
- PHP 小方法之 写日志方法
- 剑指offer题目51-60
- Cannot export AX project in AX7
- 12-1 上午mysql 基本语句
- 使用BusyBox制作Linux根文件系统
- 树莓派实现TimeMachine以及samba服务
- Http请求通信(工具类)
- 高频dom操作和页面性能优化(转载)
- 微信小程序——微信支付
- 移动App,AJAX异步请求,实现简单的增、删、改、查
- SQL知识点
- java项目发布到linux服务器,tomcat正常启动但没加载项目
- maven install 错误
- Django 分页器
- ArcGIS AddIN Sample学习笔记
- spring boot 2.0 源码分析(一)
- Python基础教程学习笔记:第一章 基础知识
- JDBC核心API