标签:without can java vat ref time ted html void
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:
target
) will be positive integers.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,就可以提前终止回溯了。
时间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 }
[LeetCode] 39. Combination Sum
标签:without can java vat ref time ted html void
原文地址:https://www.cnblogs.com/cnoodle/p/12996790.html