Skip to content

Commit ccf18ab

Browse files
solves combination sum ii
1 parent 79fb2d4 commit ccf18ab

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
| 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku) | [![Java](assets/java.png)](src/ValidSudoku.java) | |
4444
| 38 | [Count and Say](https://leetcode.com/problems/count-and-say) | [![Java](assets/java.png)](src/CountAndSay.java) [![Python](assets/python.png)](python/count_and_say.py) | |
4545
| 39 | [Combination Sum](https://leetcode.com/problems/combination-sum) | [![Java](assets/java.png)](src/CombinationSum.java) | |
46+
| 40 | [Combination Sum II](https://leetcode.com/problems/combination-sum-ii) | [![Java](assets/java.png)](src/CombinationSumII.java) | |
4647
| 53 | [Maximum SubArray](https://leetcode.com/problems/maximum-subarray) | [![Java](assets/java.png)](src/MaximumSubArray.java) [![Python](assets/python.png)](python/maximum_sum_subarray.py) | |
4748
| 58 | [Length of Last Word](https://leetcode.com/problems/length-of-last-word) | [![Java](assets/java.png)](src/LengthOfLastWord.java) [![Python](assets/python.png)](python/length_of_last_word.py) | |
4849
| 66 | [Plus One](https://leetcode.com/problems/plus-one) | [![Java](assets/java.png)](src/PlusOne.java) [![Python](assets/python.png)](python/plus_one.py) | |

Diff for: src/CombinationSumII.java

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// https://leetcode.com/problems/combination-sum-ii
2+
// T: O(2^N)
3+
// S: O(N)
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.LinkedList;
8+
import java.util.List;
9+
10+
public class CombinationSumII {
11+
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
12+
List<List<Integer>> results = new ArrayList<>();
13+
LinkedList<Integer> comb = new LinkedList<>();
14+
Arrays.sort(candidates);
15+
backtrack(candidates, comb, target, 0, results);
16+
return results;
17+
}
18+
19+
private void backtrack(int[] candidates, LinkedList<Integer> comb,
20+
int remain, int curr,
21+
List<List<Integer>> results) {
22+
if (remain == 0) {
23+
results.add(new ArrayList<Integer>(comb));
24+
return;
25+
}
26+
27+
for (int nextCurr = curr; nextCurr < candidates.length; ++nextCurr) {
28+
if (nextCurr > curr && candidates[nextCurr] == candidates[nextCurr - 1])
29+
continue;
30+
31+
int pick = candidates[nextCurr];
32+
if (remain - pick < 0) break;
33+
34+
comb.addLast(pick);
35+
backtrack(candidates, comb, remain - pick, nextCurr + 1, results);
36+
comb.removeLast();
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)