LeetCode#39 Combination Sum
2015-08-04 16:12
295 查看
Problem Definition:
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:
Solution:
回溯法(DFS)。每个元素可以被重复用很多次,因此DFS时子节点应当包括当前节点本身(或者说是再构造一个新的节点,包含了当前元素)。
另一个问题 Combination Sum,则不应该包括当前节点本身。
另外,在cur的for循环里,如果nt已经小于零,则不继续进行没必要的递归,也因为外围的 if-else 就不用处理target<0的情况了。
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
2,3,6,7and target
7,
A solution set is:
[7]
[2, 2, 3]
Solution:
回溯法(DFS)。每个元素可以被重复用很多次,因此DFS时子节点应当包括当前节点本身(或者说是再构造一个新的节点,包含了当前元素)。
另一个问题 Combination Sum,则不应该包括当前节点本身。
# @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum(self, candidates, target): candidates.sort() res=[] self.cur(candidates, target, 0, [], res) return res def cur(self, nums, target, index, localArr, res): if target==0: res.append(localArr[:]) else: for i in range(index, len(nums)): nt=target-nums[i] if nt>=0: localArr.append(nums[i]) self.cur(nums, nt, i, localArr, res) localArr.pop() else: break
另外,在cur的for循环里,如果nt已经小于零,则不继续进行没必要的递归,也因为外围的 if-else 就不用处理target<0的情况了。
相关文章推荐
- vector::erase()方法的详细介绍及问题解答的问题
- HDU 5344 多校赛1002 MZL's xor
- POJ 3264 Balanced Lineup RMQ问题 ST算法 O(1)查找区间最值
- 二叉树非递归遍历
- POJ 3620--Avoid The Lakes【DFS】
- Android SDK Mirror
- Spring知识点小结
- leetcode——Count Complete Tree Nodes
- Http基础(记忆笔记)
- 高效算法——B 抄书 copying books,uva714
- BaseAdapter的使用步骤以及setTag和getTag的作用
- windows安卓NDK编程
- Yslow-23条规则
- HBase分享系列(2)--写入细节
- Hibernate 学习笔记
- R语言饼图的绘制
- Android4.4深入浅出之SurfaceFlinger总体结构
- js前台分页显示后端JAVA数据响应
- 区间覆盖问题 SDUT2074
- uva 1613 Keep the Customer Satisfied