[LeetCode] 39. Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

Input: candidates = [2], target = 1
Output: []

Constraints:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40

组合总和。

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这个题依然是 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 }

 

LeetCode 题目总结

posted @ 2020-05-31 11:13  CNoodle  阅读(448)  评论(0编辑  收藏  举报