-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum.java
More file actions
35 lines (31 loc) · 1.07 KB
/
CombinationSum.java
File metadata and controls
35 lines (31 loc) · 1.07 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
import java.util.*;
public class CombinationSum {
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
Stack<Integer> stack = new Stack<>();
int index = 0;
int sum = 0;
while (!stack.isEmpty() || index < candidates.length) {
if (sum == target) {
result.add(new ArrayList<>(stack));
if (stack.isEmpty()) break;
sum -= stack.pop();
index++;
} else if (sum > target || index >= candidates.length) {
if (stack.isEmpty()) break;
sum -= stack.pop();
index++;
} else {
stack.push(candidates[index]);
sum += candidates[index];
}
}
return result;
}
public static void main(String[] args) {
int[] candidates = {2, 3, 6, 7};
int target = 7;
List<List<Integer>> res = combinationSum(candidates, target);
System.out.println(res);
}
}