题目:
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
- 所有数字(包括目标数)都是正整数。
- 解集不能包含重复的组合。
示例 1:
输入: candidates =[10,1,2,7,6,1,5], target =8, 所求解集为: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5, 所求解集为: [ [1,2,2], [5] ]
解题思路:
通过i+1防止对同一元素重复提取,对candidates排序然后判断当前元素和上一元素防止重复计算。
代码实现:
class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> result = new LinkedList<List<Integer>>(); List<Integer> list = new LinkedList<Integer>(); Arrays.sort(candidates); dfs(candidates, target, 0, result, list, 0); return result; } private void dfs(int[] candidates, int target, int sum, List<List<Integer>> result, List<Integer> list, int start) { if (sum > target) return; else if (sum == target) { result.add(new LinkedList<Integer>(list)); return; } for (int i = start; i < candidates.length; i ++) { if(i > start && candidates[i] == candidates[i-1]) continue; sum += candidates[i]; list.add(candidates[i]); dfs(candidates, target, sum, result, list, i + 1); sum -= candidates[i]; list.remove(list.size() - 1); } } }

本文介绍了一种解决组合总和问题的方法,该问题要求从给定数组中找出所有可能的组合,使得这些组合的元素之和等于指定的目标值。文章详细阐述了解题思路,并提供了具体的代码实现。
5万+

被折叠的 条评论
为什么被折叠?



