【LeetCode题意分析&解答】39. Combination Sum
2016-03-17 23:03
316 查看
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
题意分析:
本题是给定一个数字集合(可能有重复)和一个目标值,让你找出所有可能的组合,使之和为目标值。所有的数字可以使用无限次,要求得到的组合不能有重复,并且组合里面的数字必须是升序。
解答:
思路是循环拿每个数字去迭代,找出所有的组合,满足条件返回,不满足退回上一步继续下一个数字的尝试。看特征,仍然是用回溯法的思路去做。
AC代码:
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
题意分析:
本题是给定一个数字集合(可能有重复)和一个目标值,让你找出所有可能的组合,使之和为目标值。所有的数字可以使用无限次,要求得到的组合不能有重复,并且组合里面的数字必须是升序。
解答:
思路是循环拿每个数字去迭代,找出所有的组合,满足条件返回,不满足退回上一步继续下一个数字的尝试。看特征,仍然是用回溯法的思路去做。
AC代码:
class Solution(object): def combinationSum(self, candidates, target): ret_list = [] def backtracing(target, candidates, index, temp_list): if target == 0: ret_list.append(temp_list) elif target > 0: for i in xrange(index, len(candidates)): backtracing(target - candidates[i], candidates, i, temp_list + [candidates[i]]) backtracing(target, sorted(list(set(candidates))), 0, []) return ret_list
相关文章推荐
- C#高级编程 (第六版) 学习 第六章:运算符和类型强制转换
- DataTable +chart控件
- 在项目中混合使用CASE 、JOIN等sql语句
- 2016年技术面试总结
- 设计模式C++学习笔记之十九(State状态模式)
- 利用C语言实现动态顺序表
- N!高精度
- SAP Sybase参数调整
- Linux Kernel 学习路线
- 安装 Apache 出现 <OS 10013> 以一种访问权限不允许的方式做了一个访问套接字的尝试
- JavaScript中with语句的优缺点
- 国内计算机类期刊 SCI收录:
- 设计模式C++学习笔记之十八(Visitor访问者模式)
- 127. Word Ladder LeetCode
- hud 2549 壮志难酬
- AsyncCallback BeginInvode endinvode 异步调用
- 复利计算器开发总结
- SPOJ COT2 Count on a tree II 树上莫队算法
- 安卓第十五天笔记-图形图像一些简单处理
- [nodejs] nodejs开发个人博客(七)后台登陆