-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathCombination Sum.java
More file actions
69 lines (62 loc) · 2.45 KB
/
Combination Sum.java
File metadata and controls
69 lines (62 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Problem: Find all combinations of numbers from array that sum to target.
* Numbers can be reused, and duplicates in result should be avoided.
* Algorithm: Backtracking - explore all possible combinations and track valid ones.
* Time Complexity: O(2^n) in worst case for exploring all combinations
* Space Complexity: O(n) for recursion depth + output space
*/
public class Solution {
/**
* Finds all unique combinations that sum to target B.
*
* @param A the list of candidate numbers (may contain duplicates)
* @param B the target sum
* @return ArrayList of all unique combinations that sum to B
*
* Example:
* A = [3, 6, 2], B = 9
* Output: [[3, 3, 3], [3, 6], [2, 2, 2, ...]] or similar
*/
public ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B) {
// Step 1: Sort array for consistency and easier duplicate handling
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
Collections.sort(A);
// Step 2: Start backtracking from index 0
// Current combination, remaining sum, and starting index
helper(A, ans, new ArrayList<>(), B, 0);
// Step 3: Return all valid combinations found
return new ArrayList<>(ans);
}
/**
* Backtracking helper to explore all combinations.
*
* @param a the candidate numbers array
* @param ans the result list of all valid combinations
* @param curr the current combination being built
* @param b the remaining sum needed
* @param idx the starting index to avoid duplicates
*/
private void helper(ArrayList<Integer> a, ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> curr, int b, int idx) {
// Step 1: If remaining sum becomes negative, stop this path
if (b < 0) {
return;
}
// Step 2: If remaining sum becomes 0, we found a valid combination
if (b == 0) {
// Add only if this combination is not already in the result
if (!ans.contains(curr)) {
ans.add(new ArrayList<>(curr));
}
return;
}
// Step 3: Try adding each number starting from idx (allows reuse)
for (int i = idx; i < a.size(); i++) {
// Step 3a: Choose - add current number to combination
curr.add(a.get(i));
// Step 3b: Explore - recurse with same index (allows reuse) and reduced sum
helper(a, ans, curr, b - a.get(i), i);
// Step 3c: Un-choose - backtrack by removing the added number
curr.remove(curr.size() - 1);
}
}
}