Skip to content

Commit cfce674

Browse files
committed
solve 40.combination-sum-ii
1 parent 2a9fc42 commit cfce674

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

vscode/40.combination-sum-ii.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/*
2+
* @lc app=leetcode id=40 lang=java
3+
*
4+
* [40] Combination Sum II
5+
*
6+
* https://leetcode.com/problems/combination-sum-ii/description/
7+
*
8+
* algorithms
9+
* Medium (43.08%)
10+
* Likes: 1009
11+
* Dislikes: 50
12+
* Total Accepted: 244.2K
13+
* Total Submissions: 566.1K
14+
* Testcase Example: '[10,1,2,7,6,1,5]\n8'
15+
*
16+
* Given a collection of candidate numbers (candidates) and a target number
17+
* (target), find all unique combinations in candidates where the candidate
18+
* numbers sums to target.
19+
*
20+
* Each number in candidates may only be used once in the combination.
21+
*
22+
* Note:
23+
*
24+
*
25+
* All numbers (including target) will be positive integers.
26+
* The solution set must not contain duplicate combinations.
27+
*
28+
*
29+
* Example 1:
30+
*
31+
*
32+
* Input: candidates = [10,1,2,7,6,1,5], target = 8,
33+
* A solution set is:
34+
* [
35+
* ⁠ [1, 7],
36+
* ⁠ [1, 2, 5],
37+
* ⁠ [2, 6],
38+
* ⁠ [1, 1, 6]
39+
* ]
40+
*
41+
*
42+
* Example 2:
43+
*
44+
*
45+
* Input: candidates = [2,5,2,1,2], target = 5,
46+
* A solution set is:
47+
* [
48+
* [1,2,2],
49+
* [5]
50+
* ]
51+
*
52+
*
53+
*/
54+
class Solution {
55+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
56+
List<List<Integer>> list = new ArrayList<>();
57+
Arrays.sort(candidates);
58+
backtrack(list, new ArrayList<>(), candidates, target, 0);
59+
return list;
60+
}
61+
62+
public void backtrack(List<List<Integer>> list, List<Integer> track, int[] candidates, int remain, int start) {
63+
if (remain < 0) return;
64+
if (remain == 0) {
65+
list.add(new ArrayList<>(track));
66+
} else {
67+
for (int i = start; i < candidates.length; i++) {
68+
if (i > start && candidates[i] == candidates[i - 1]) continue;
69+
track.add(candidates[i]);
70+
backtrack(list, track, candidates, remain - candidates[i], i + 1);
71+
track.remove(track.size() - 1);
72+
}
73+
}
74+
}
75+
}
76+

0 commit comments

Comments
 (0)