|
3 | 3 | import java.util.ArrayList;
|
4 | 4 | import java.util.Arrays;
|
5 | 5 | import java.util.List;
|
6 |
| -/** |
7 |
| - * 40. Combination Sum II |
8 |
| - * |
9 |
| - * Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. |
10 |
| - * Each number in C may only be used once in the combination. |
11 | 6 |
|
12 |
| - Note: |
13 |
| - All numbers (including target) will be positive integers. |
14 |
| - The solution set must not contain duplicate combinations. |
15 |
| - For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, |
16 |
| - A solution set is: |
17 |
| - [ |
18 |
| - [1, 7], |
19 |
| - [1, 2, 5], |
20 |
| - [2, 6], |
21 |
| - [1, 1, 6] |
22 |
| - ] |
23 |
| - */ |
24 | 7 | public class _40 {
|
25 | 8 |
|
26 | 9 | public static class Solution1 {
|
27 |
| - public List<List<Integer>> combinationSum2(int[] candidates, int target) { |
28 |
| - List<List<Integer>> result = new ArrayList(); |
29 |
| - Arrays.sort(candidates); |
30 |
| - backtracking(candidates, 0, result, target, new ArrayList()); |
31 |
| - return result; |
32 |
| - } |
| 10 | + public List<List<Integer>> combinationSum2(int[] candidates, int target) { |
| 11 | + List<List<Integer>> result = new ArrayList(); |
| 12 | + Arrays.sort(candidates); |
| 13 | + backtracking(candidates, 0, result, target, new ArrayList()); |
| 14 | + return result; |
| 15 | + } |
33 | 16 |
|
34 |
| - void backtracking(int[] candidates, int start, List<List<Integer>> result, int target, |
35 |
| - List<Integer> curr) { |
36 |
| - if (target > 0) { |
37 |
| - for (int i = start; i < candidates.length; i++) { |
38 |
| - if (candidates[i] > target || (i > start && candidates[i - 1] == candidates[i])) { |
39 |
| - continue; |
| 17 | + void backtracking(int[] candidates, int start, List<List<Integer>> result, int target, |
| 18 | + List<Integer> curr) { |
| 19 | + if (target > 0) { |
| 20 | + for (int i = start; i < candidates.length; i++) { |
| 21 | + if (candidates[i] > target || (i > start && candidates[i - 1] == candidates[i])) { |
| 22 | + continue; |
| 23 | + } |
| 24 | + curr.add(candidates[i]); |
| 25 | + backtracking(candidates, i + 1, result, target - candidates[i], curr); |
| 26 | + curr.remove(curr.size() - 1); |
| 27 | + } |
| 28 | + } else if (target == 0) { |
| 29 | + result.add(new ArrayList(curr)); |
40 | 30 | }
|
41 |
| - curr.add(candidates[i]); |
42 |
| - backtracking(candidates, i + 1, result, target - candidates[i], curr); |
43 |
| - curr.remove(curr.size() - 1); |
44 |
| - } |
45 |
| - } else if (target == 0) { |
46 |
| - result.add(new ArrayList(curr)); |
47 | 31 | }
|
48 |
| - } |
49 | 32 | }
|
50 | 33 | }
|
0 commit comments