-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
46 lines (44 loc) · 1.15 KB
/
Copy pathsolution.java
File metadata and controls
46 lines (44 loc) · 1.15 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
// 40. Combination Sum II
// https://leetcode.com/problems/combination-sum-ii/
// Medium | Java | Accepted 2025-12-13
// Runtime 7 ms | Memory 45.2 MB
class Solution {
List<List<Integer>> ans = new ArrayList<>();
int[] cand;
int targ;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
cand = candidates;
targ = target;
recurse(0, 0, new ArrayList<>());
return ans;
}
public void recurse(int index, int sum, List<Integer> temp)
{
if(index == cand.length || sum >=targ)
{
if(sum==targ)
{
ans.add(new ArrayList<>(temp));
}
return;
}
temp.add(cand[index]);
recurse(index+1, sum+cand[index], temp);
temp.remove(temp.size()-1);
int i = index;
while(i<cand.length && cand[i]==cand[index])
{
i++;
}
if(i>=cand.length)
{
if(sum==targ)
{
ans.add(new ArrayList<>(temp));
}
return;
}
recurse(i, sum, temp);
}
}