@@ -200,6 +200,12 @@ private void backtrack(int[] nums, boolean[] visited, List<Integer> list, List<L
200200> - 所有数字(包括 ` target ` )都是正整数。
201201> - 解集不能包含重复的组合。
202202
203+ ``` html
204+ given candidate set [2, 3, 6, 7] and target 7,
205+ A solution set is:
206+ [[7],[2, 2, 3]]
207+ ```
208+
203209``` java
204210public List<List<Integer > > combinationSum(int [] candidates, int target) {
205211 List<Integer > answer = new ArrayList ();
@@ -234,6 +240,66 @@ private void backtrack(int[] candidates, int pos, int target, List<Integer> answ
234240}
235241```
236242
243+ > [ 39. 组合总和-II] ( https://leetcode.com/problems/combination-sum-ii/ )
244+ >
245+ > 给定一个** 重复元素** 的数组 ` candidates ` 和一个目标数 ` target ` ,找出 ` candidates ` 中所有可以使数字和为 ` target ` 的组合。
246+ >
247+ > ` candidates ` 中的数字只能使用一次。
248+ >
249+ > ** 说明:**
250+ >
251+ > - 所有数字(包括 ` target ` )都是正整数。
252+ > - 解集不能包含重复的组合。
253+
254+ ``` html
255+ For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
256+ A solution set is:
257+ [
258+ [1, 7],
259+ [1, 2, 5],
260+ [2, 6],
261+ [1, 1, 6]
262+ ]
263+ ```
264+
265+ ``` java
266+ public List<List<Integer > > combinationSum2(int [] candidates, int target) {
267+ List<Integer > answer = new ArrayList<> ();
268+ List<List<Integer > > result = new ArrayList<> ();
269+ boolean [] visited = new boolean [candidates. length];
270+ // 先排序
271+ Arrays . sort(candidates);
272+ backtracking(result, answer, candidates, target, 0 ,visited);
273+ return result;
274+ }
275+
276+ public void backtracking(List<List<Integer > > result, List<Integer > answer, int [] candidates, int target, int pos, boolean [] visited){
277+
278+ if (target == 0 ){
279+ result. add(new ArrayList<Integer > (answer));
280+ }
281+
282+ for (int i = pos; i < candidates. length; i++ ){
283+ // 剪枝:后续元素都比目标大,直接break(比continue要快)
284+ if (candidates[i] > target) {
285+ break ;
286+ }
287+ // 上一个元素和当前相同,并且没有访问过就跳过
288+ if (i != 0 && candidates[i] == candidates[i- 1 ] && ! visited[i- 1 ]){
289+ continue ;
290+ }
291+ // 添加元素
292+ answer. add(candidates[i]);
293+ visited[i] = true ;
294+ // 元素不可重复取,从下一个位置继续
295+ backtracking(result, answer, candidates, target- candidates[i], i+ 1 , visited);
296+ // 移除元素
297+ visited[i] = false ;
298+ answer. remove(answer. size()- 1 );
299+ }
300+ }
301+ ```
302+
237303#### 电话号码的字母组合
238304
239305> [ 17. 电话号码的字母组合] ( https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/ )
0 commit comments