
题目
给定一个数组 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] ]
解题思路
因为做了上一道题,这道题其实只是上一道题目的去重而已。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { if(target < 0) return null; List<List<Integer>> res = new ArrayList<>(); Arrays.sort(candidates); dfs(res, candidates, new ArrayList<Integer>(), target, 0); return res; } public void dfs(List<List<Integer>> res, int[] candidates, List<Integer> tmp, int target, int index) { if(target == 0) { res.add(tmp); return; } if(target < candidates[0]) return ; for(int i = index; i < candidates.length && candidates[i] <= target; i++) { //去重 if (i > index && candidates[i] == candidates[i - 1]) continue; List<Integer> list = new ArrayList<>(tmp); list.add(candidates[i]); dfs(res, candidates, list, target-candidates[i], i+1); } } }
|
提交结果
成功
显示详情
执行用时 : 6 ms, 在Combination Sum II的Java提交中击败了98.24% 的用户
内存消耗 : 38.9 MB, 在Combination Sum II的Java提交中击败了80.83% 的用户
近期评论