-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberCombination.java
More file actions
27 lines (22 loc) · 843 Bytes
/
Copy pathNumberCombination.java
File metadata and controls
27 lines (22 loc) · 843 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
import java.util.*;
class NumberCombination {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> answers = new ArrayList();
Arrays.sort(candidates);
dfs(answers, new ArrayList(), candidates, target, 0);
return answers;
}
public void dfs(List<List<Integer>> answers, List<Integer> temp, int[] candidates, int target, int index) {
if(target < 0) return;
if(target == 0) {
answers.add(new ArrayList(temp));
return;
}
for(int i=index; i< candidates.length; i++) {
if(i>index && candidates[i]==candidates[i-1]) continue;
temp.add(candidates[i]);
dfs(answers, temp, candidates, target-candidates[i], i+1);
temp.remove(temp.size()-1);
}
}
}