Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
, A solution set is: [ [7], [2,2,3] ]Example 2:
Input: candidates = [2,3,5],
target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ]
组合总和。这个题依然是backtracking系列里面需要背下来的题目。既然是求什么样的组合的sum能等于target,那么helper函数的退出条件就是看看什么样的组合的sum == target。同时,为了剪枝/加速,如果当前的sum大于target,就可以提前终止回溯了。
注意21行为什么递归到下一层的时候还是从i开始是因为数字可以被重复利用。这个地方跟40题还是有点区别的。
时间O(2^n)
空间O(n)
Java实现
1 class Solution { 2 public List<List<Integer>> combinationSum(int[] candidates, int target) { 3 List<List<Integer>> res = new ArrayList<>(); 4 if (candidates == null || candidates.length == 0) { 5 return res; 6 } 7 helper(res, new ArrayList<>(), candidates, target, 0); 8 return res; 9 } 10 11 private void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start) { 12 if (target < 0) { 13 return; 14 } 15 if (target == 0) { 16 res.add(new ArrayList<>(list)); 17 return; 18 } 19 for (int i = start; i < candidates.length; i++) { 20 list.add(candidates[i]); 21 helper(res, list, candidates, target - candidates[i], i); 22 list.remove(list.size() - 1); 23 } 24 } 25 }