leetcode -- Combination Sum III -- 重点,dfs回溯模板
2015-12-14 14:25
393 查看
https://leetcode.com/problems/combination-sum-iii/
简单。总结自己的回溯模板
my code:
简单。总结自己的回溯模板
class Solution(object): def dfs(self, candidates, start, end, target_val, subres, res):#输入参数 if sum(subres) == target: res.append(subres[:])#这里注意要赋值,因为这里没有用stack,其实不复制也可以。但是养成好习惯 return else: i = start#第一个子节点 while i < end: if sum(subres) + candidates[i] <= target_val:#试探第i个子节点是否满足约束条件, self.dfs(candidates, i + 1, end, target, subres + [candidates[i]], res) else:#如果不满足,因为是sorted candidates,所以可以忽略后面的子节点。相当于break return i += 1#不要忘记 def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] self.dfs(sorted(candidates), 0, 9, n, k, [], res)#这里candidates一定要sorted return res
my code:
class Solution(object): def dfs(self, candidates, start, end, target_val, target_lvl, subres, res): if sum(subres) == target_val and len(subres) == target_lvl: res.append(subres[:]) return else: i = start while i < end: if len(subres) + 1 <= target_lvl and sum(subres) + candidates[i] <= target_val: self.dfs(candidates, i + 1, end, target_val, target_lvl, subres + [candidates[i]], res) else: return i += 1 def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ res = [] self.dfs([x + 1 for x in xrange(9)], 0, 9, n, k, [], res) return res
自己code重写
class Solution(object): def dfs(self, depth, candidates, start, end, k, target, subres, res): cur_sum = sum(subres) if depth == k : if cur_sum == target and subres not in res: res.append(subres) return for i in xrange(start, end): if cur_sum + candidates[i] <= target:#这里要有等于号 self.dfs(depth + 1, candidates, i+1, end, k, target, subres + [candidates[i]], res) def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[int]] """ candidates = [i + 1 for i in xrange(9)] candidates.sort() res = [] self.dfs(0, candidates, 0, len(candidates), k, n, [], res) return res
相关文章推荐
- mysql 数据库处理高并发、 大数据量 .日常军规
- 阿里云助力合作伙伴帮助政府、企业体验云计算大数据魅力!
- coherence初识
- Android图片、文字国际化
- redis 连接池类
- 安装 Node.js
- 服务器负载均衡解决方案
- 基于lucene实现自己的推荐引擎
- oracle函数--关于日期
- 图像处理算法基础(四)---中值滤波自实现及opencv函数
- QT中的JSON应用
- MySQL proxy读写分离如何运行
- mysql count group by统计条数方法
- spring AspectJ的Execution表达式
- php-fpm ssl证书
- 轮播效果(margin-left/top)移动
- 【CodeForces 606A】A -特别水的题1-Magic Spheres
- 深入学习spring:注解
- 启动自己另一个程序的activity
- gradle构建android项目详解