-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0039CombinationSum.java
More file actions
34 lines (29 loc) · 1007 Bytes
/
_0039CombinationSum.java
File metadata and controls
34 lines (29 loc) · 1007 Bytes
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
package com.heatwave.leetcode.problems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _0039CombinationSum {
static class Solution {
List<Integer> temp = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, 0, target);
return ans;
}
private void backtracking(int[] nums, int index, int target) {
int sum = temp.stream().reduce(Integer::sum).orElse(0);
if (target == sum) {
ans.add(new ArrayList<>(temp));
}
if (sum > target) {
return;
}
for (int i = index; i < nums.length; i++) {
temp.add(nums[i]);
backtracking(nums, i, target);
temp.remove(temp.size() - 1);
}
}
}
}