Combination Sum I
Problem
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.
Notice
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.
Example
given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
Note
基本思路与Combinations一致,递归模板详见:https://segmentfault.com/a/11...
有两个点需要注意:在组合中的数必须是升序排列,所以在调用dfs函数之前要先排序;另外,由于组合里允许有重复数,dfs调用自身时,初始位start(=i)
的位置不变,依然从i
开始,只需将target
减小num[i]
即可。
Solution
Recursion 26ms
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
helper(candidates, 0, target, new ArrayList<Integer>());
return res;
}
public void helper(int[] c, int start, int t, List<Integer> pre) {
if (t < 0) return;
if (t == 0) res.add(pre);
for (int i = start; i < c.length; i++) {
List<Integer> cur = new ArrayList<Integer>(pre);
cur.add(c[i]);
helper(c, i, t-c[i], cur);
}
}
}
Combination Sum II
Problem
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Notice
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.
Example
Given candidate set [10,1,6,7,2,1,5] and target 8,
A solution set is:
[
[1,7],
[1,2,5],
[2,6],
[1,1,6]
]
Note
和Combination Sum I唯一的不同是组合中不能存在重复的元素,因此,在dfs递归时将初始位+1
即可。
Solution
public class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum2(int[] num, int target) {
Arrays.sort(num);
helper(num, 0, target, new ArrayList<Integer>());
return res;
}
public void helper(int[] num, int start, int target, List<Integer> pre) {
if (target < 0) return;
if (target == 0) {
res.add(pre);
return;
}
for (int i = start; i < num.length; i++) {
if (i > start && num[i] == num[i-1]) continue;
List<Integer> cur = new ArrayList<Integer> (pre);
cur.add(num[i]);
helper(num, i+1, target-num[i], cur);
}
}
}
Combination Sum III & IV link: here
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。