Skip to content

Commit

Permalink
solution(java): 40. Combination Sum II
Browse files Browse the repository at this point in the history
40. Combination Sum II
- Java
  • Loading branch information
godkingjay authored Oct 29, 2023
2 parents d4cfdf4 + 938d50e commit f880f5e
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Medium/40. Combination Sum II/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# LeetCode 40. Combination Sum II

## Problem Description
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.

Each number in `candidates` may only be used once in the combination.

**Note:** The solution set must not contain duplicate combinations.

### Test Cases

**Example 1:**

> **Input:** candidates = [10,1,2,7,6,1,5], target = 8
>
> **Output:**
>
> [
>
> [1,1,6],
>
> [1,2,5],
>
> [1,7],
>
> [2,6]
>
> ]
**Example 2:**

> **Input:** candidates = [2,5,2,1,2], target = 5
>
> **Output:**
>
> [
>
> [1,2,2],
>
> [5]
>
> ]
### Constraints:

`1 <= candidates.length <= 100`

`1 <= candidates[i] <= 50`

`1 <= target <= 30`

### Link

https://leetcode.com/problems/combination-sum-ii/
37 changes: 37 additions & 0 deletions Medium/40. Combination Sum II/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(candidates);

backtrack(result, new ArrayList<>(), candidates, target, 0);

return result;
}

private void backtrack(List<List<Integer>> result, List<Integer> current, int[] candidates, int target, int start) {
if (target == 0) {
result.add(new ArrayList<>(current));
return;
}

for (int i = start; i < candidates.length; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}

int num = candidates[i];

if (num > target) {
break;
}

current.add(num);
backtrack(result, current, candidates, target - num, i + 1);
current.remove(current.size() - 1);
}
}
}

0 comments on commit f880f5e

Please sign in to comment.