forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationsum.java
More file actions
executable file
·45 lines (40 loc) · 1.57 KB
/
combinationsum.java
File metadata and controls
executable file
·45 lines (40 loc) · 1.57 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
public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
// Start typing your Java solution below
// DO NOT write main() function
HashMap<Integer, ArrayList<ArrayList<Integer>>> numberToComb =
new HashMap<Integer, ArrayList<ArrayList<Integer>>>();
ArrayList<Integer> cda = new ArrayList<Integer>();
for(int i=0;i<candidates.length;i++){
cda.add(candidates[i]);
}
Collections.sort(cda);
HashSet<Integer> hs = new HashSet<Integer>(cda);
for(int i=1;i<=target;i++){
numberToComb.put(i, new ArrayList<ArrayList<Integer>>());
}
for(int i=1;i<=target;i++){
if(hs.contains(i)){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(i);
numberToComb.get(i).add(tmp);
}
if(i==target){
break;
}
for(Integer k : cda){
if( k+i<=target ){
for(ArrayList<Integer> ar : numberToComb.get(i)){
if(k<ar.get(ar.size()-1)){
continue;
}
ArrayList<Integer> arnew = new ArrayList<Integer>(ar);
arnew.add(k);
numberToComb.get(k+i).add(arnew);
}
}
}
}
return numberToComb.get(target);
}
}