Permutation Sequence
来源:互联网 发布:机甲风暴java 编辑:程序博客网 时间:2024/05/18 02:21
leetcode第60题,全排列的变种,要求找出n个数字全排列后按字典序的第k个数字。
第一种直观思路,直接生成n个数字的全排列,然后找到第k个就可以了,使用回溯,可以顺理成章地生成按字典序排列的全排列数字,顺序是不用太过关心的,但是这个方法跑不过大数据,因为复杂度太高。
def getPermutation(n, k): visit = [False] * 10 def dfs(seq,ans): import copy if len(seq) == n+1: tmp = copy.deepcopy(seq[1:]) ans.append(tmp) return for i in range(1,n+1): if visit[i] == False: seq.append(i) visit[i] = True dfs(seq,ans) del seq[-1] visit[i] = False seq = [0] ans = [] dfs(seq,ans) return ''.join(map(str,ans[k-1]))
第二种思路是,既然是找第k个,而且按照字典序,说明有规律可循,n个数全排列有n!个,如果第一位确定,那么还有(n-1)!种可能,我们可以不断地逼近这个数字,就可以直接找到。
具体思路讲的不太清楚,参考找个链接应该就会有直观认识了。http://www.cnblogs.com/TenosDoIt/p/3721918.html
class Solution(object): def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ import math factor = [math.factorial(i) for i in range(1,n+1)] print factor visit = [False]*10 ans = '' i = n-2 k -= 1 while i >= -1: tmp = k/factor[i] for j in range(1,n+1): if visit[j] == False: tmp -= 1 if tmp < 0: break visit[j] = True ans += str(j) k %= factor[i] i -= 1 return ans
0 0
- 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
- Web前端面试指导(三十三):谈谈你对模块化开发的理解?
- linux下如何实现mysql数据库每天自动备份定时备份
- 极限学习机代码注释翻译
- 数据分析大咖一日行
- mac os x 10.8 mountain lion 创建/home目录
- Permutation Sequence
- LeetCde----40. Combination Sum II
- LeetCode笔记:415. Add Strings
- php四种基本算法
- android支持桌面横屏
- JavaScript强化教程——canvas
- 使用BroadcastReceiver监听网络状态
- 安装多个Xcdoe使用cocoapods 因为路径造成Unable to add a source with url错误解决
- 100天土鸡饲养计划(61)