You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/main/java/g0001_0100/s0039_combination_sum/readme.md
+52-1Lines changed: 52 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -33,4 +33,55 @@ The test cases are generated such that the number of unique combinations that su
33
33
*`1 <= candidates.length <= 30`
34
34
*`2 <= candidates[i] <= 40`
35
35
* All elements of `candidates` are **distinct**.
36
-
*`1 <= target <= 40`
36
+
*`1 <= target <= 40`
37
+
38
+
To solve the "Combination Sum" problem in Java with a `Solution` class, we can follow these steps:
39
+
40
+
1. Define a `Solution` class.
41
+
2. Define a method named `combinationSum` that takes an array of integers `candidates` and an integer `target` as input and returns a list of lists containing all unique combinations of `candidates` where the chosen numbers sum to `target`.
42
+
3. Implement backtracking to explore all possible combinations of candidates.
43
+
4. Sort the `candidates` array to ensure that duplicates are grouped together.
44
+
5. Create a recursive helper method named `backtrack` that takes parameters:
45
+
- A list to store the current combination.
46
+
- An integer representing the starting index in the `candidates` array.
47
+
- The current sum of the combination.
48
+
6. In the `backtrack` method:
49
+
- If the current sum equals the target, add the current combination to the result list.
50
+
- Iterate over the candidates starting from the current index.
51
+
- Add the current candidate to the combination.
52
+
- Recursively call the `backtrack` method with the updated combination, index, and sum.
53
+
- Remove the last added candidate from the combination to backtrack.
54
+
7. Call the `backtrack` method with an empty combination list, starting index 0, and sum 0.
55
+
8. Return the result list containing all unique combinations.
for (int i = start; i < candidates.length && candidates[i] <= target; i++) {
79
+
combination.add(candidates[i]);
80
+
backtrack(result, combination, candidates, target - candidates[i], i); // Use the same candidate again
81
+
combination.remove(combination.size() -1); // Backtrack by removing the last candidate
82
+
}
83
+
}
84
+
}
85
+
```
86
+
87
+
This implementation provides a solution to the "Combination Sum" problem in Java. It explores all possible combinations of candidates using backtracking and returns the unique combinations whose sum equals the target.
0 commit comments