-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum.java
More file actions
61 lines (57 loc) · 1.98 KB
/
combination_sum.java
File metadata and controls
61 lines (57 loc) · 1.98 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
47
48
49
50
51
52
53
54
55
56
57
58
public class Solution {
ArrayList<ArrayList<Integer>> r;
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
// Start typing your Java solution below
// DO NOT write main() function
r=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> sofar=new ArrayList<Integer>();
//Arrays.sort(candidates);
c(candidates,target,sofar,0);
return r;
}
public void c(int[] cand,int target,ArrayList<Integer> sofar,int ind) {
if(target==0) {
ArrayList<Integer> cp=new ArrayList<Integer>(sofar);
r.add(cp);
return;
}
if(target<0) return; // save time
for(int i=ind;i<cand.length;i++) {
sofar.add(cand[i]); // i
c(cand,target-cand[i],sofar,i);
sofar.remove(sofar.size()-1);
}
}
}
public class Solution {
ArrayList<ArrayList<Integer>> r;
ArrayList<Integer> d;
public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
// Start typing your Java solution below
// DO NOT write main() function
r=new ArrayList<ArrayList<Integer>>();
d=new ArrayList<Integer>();
ArrayList<Integer> sofar=new ArrayList<Integer>();
Arrays.sort(candidates);
c(candidates,target,sofar,0);
return r;
}
public void c(int[] cand,int target,ArrayList<Integer> sofar,int ind) {
if(target==0) {
ArrayList<Integer> cp=new ArrayList<Integer>(sofar);
r.add(cp);
return;
}
if(target<cand[0]) return;
for(int i=ind;i<cand.length;i++) {
if (i>ind && cand[i] == cand[i-1]) continue;
sofar.add(cand[i]);
d.add(cand[i]);
c(cand,target-cand[i],sofar,i+1);
sofar.remove(sofar.size()-1);
//d.remove(cand[i]);
//d.remove((Integer)cand[i]);
d.remove(d.size()-1);
}
}
}