Skip to content

Commit 7951e9e

Browse files
authored
Added 039_Combination_Sum.java (qiyuangong#75)
* Added 039_Combination_Sum.java Contributed by @green-study
1 parent b3bd2dd commit 7951e9e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

java/039_Combination_Sum.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
//039_Combination_Sum
2+
class Solution {
3+
List<List<Integer>> answer = new ArrayList<List<Integer>>();
4+
5+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
6+
int clen =candidates.length;
7+
for (int i = 0; i < clen; i++) {
8+
List<Integer> tlist = new ArrayList<Integer>();
9+
tlist.add(candidates[i]);
10+
backtracking(candidates, i, 1, (target - candidates[i]), tlist);
11+
}
12+
return answer;
13+
}
14+
private void backtracking(int[] candidates, int index, int tsize, int target, List<Integer> temp) {
15+
if (target == 0) {
16+
answer.add(new ArrayList(temp));
17+
return;
18+
}
19+
20+
for (int i = index, len = candidates.length; i < len; i++) {
21+
if (candidates[i] <= target) {
22+
temp.add(candidates[i]);
23+
backtracking(candidates, i, (tsize + 1), (target - candidates[i]), temp);
24+
temp.remove(tsize);
25+
}
26+
}
27+
}
28+
}
29+

0 commit comments

Comments
 (0)