40. 组合总和 II

描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

注意:解集不能包含重复的组合。

 

 

链接

40. 组合总和 II - 力扣(LeetCode) (leetcode-cn.com)

 

解法

 1 class Solution {
 2     List<List<Integer>> res = new ArrayList<>();
 3     Deque<Integer> path = new ArrayDeque<>();
 4     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 5         if (candidates == null || candidates.length == 0) return res;
 6         Arrays.sort(candidates);
 7         BackTracking(candidates, target, 0, 0);
 8         return res;
 9     }
10 
11     public void BackTracking(int[] candidates, int target, int Sum, int Index) {
12         if (Sum > target) return;
13         if (Sum == target) {
14             res.add(new ArrayList<>(path));
15             return;
16         }
17 
18         for (int i = Index; i < candidates.length; i++) {
19             // 要对同一树层使用过的元素进行跳过,在宽度上
20             if (Index < i && candidates[i] == candidates[i - 1]) { 
21                 continue;
22             }
23             Sum += candidates[i];
24             path.add(candidates[i]);
25             BackTracking(candidates, target, Sum, i+1); // i + 1是为了去重,在深度上
26             Sum -= candidates[i];
27             path.removeLast();
28         }
29     }
30 }

 

参考

carl

posted @ 2021-12-19 22:07  DidUStudy  阅读(30)  评论(0编辑  收藏  举报