Skip to content

Commit 8597bd4

Browse files
committed
Signed-off-by: yuduozhou <[email protected]>
1 parent fda5591 commit 8597bd4

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

CombinationSum1.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
public class Solution {
2+
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
3+
// Start typing your Java solution below
4+
// DO NOT write main() function
5+
Arrays.sort(candidates);
6+
//reverse the array
7+
for (int i = 0; i < candidates.length/2; i++) {
8+
int temp = candidates[i];
9+
candidates[i] = candidates[candidates.length-1-i];
10+
candidates[candidates.length-1-i] = temp;
11+
}
12+
return cs (candidates, target, 0);
13+
}
14+
public ArrayList<ArrayList<Integer>> cs (int[] candidates, int target, int index) {
15+
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
16+
if (target == 0) {
17+
ret.add(new ArrayList<Integer>());
18+
return ret;
19+
}
20+
if (index >= candidates.length) {
21+
return null;
22+
}
23+
for (int i = 0; candidates[index] * i <= target; i++) {
24+
ArrayList<ArrayList<Integer>> r = cs (candidates, target-candidates[index] * i, index + 1);
25+
if (r != null) {
26+
//add i candidates[index] to all of the arraylists
27+
for (int j = 0; j < r.size(); j++) {
28+
for (int k = 0; k < i; k++) {
29+
r.get(j).add(candidates[index]);
30+
}
31+
}
32+
ret.addAll(r);
33+
}
34+
}
35+
return ret;
36+
}
37+
}

CombinationSum2.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Thanks to http://heartfire.cc
2+
public class Solution {
3+
public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
4+
// Start typing your Java solution below
5+
// DO NOT write main() function
6+
Arrays.sort(num);
7+
int[] backtrack = new int[num.length+1];
8+
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
9+
backtrack[0] = -1;
10+
solve (num, 0, target, backtrack, result, 0);
11+
return result;
12+
}
13+
14+
public void solve(int[] num, int sum, int target, int[] backtrack, ArrayList<ArrayList<Integer>> result, int n){
15+
//backtrack records the indexes in num array
16+
//what is my next number's index? start trying from backtrack[n] + 1 to num's end
17+
if (target == sum) {
18+
//add everything in backtrack to result
19+
ArrayList<Integer> ret = new ArrayList<Integer>();
20+
for (int i = 1; i <= n; i++) {
21+
ret.add(num[backtrack[i]]);
22+
}
23+
result.add(ret);
24+
}
25+
if (target < sum) {
26+
return;
27+
}
28+
for (int i = backtrack[n] + 1; i < num.length; i++) {
29+
backtrack[n+1] = i;
30+
solve(num, sum+num[i], target, backtrack, result, n+1);
31+
32+
while (i+1 < num.length && num[i+1] == num[i]) {
33+
i++;
34+
}
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)