Skip to content

Commit 967ac29

Browse files
committed
0039. Combination Sum V1.0
1 parent 55e8b0f commit 967ac29

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.ArrayList;
2+
import java.util.Arrays;
3+
import java.util.Deque;
4+
import java.util.LinkedList;
5+
import java.util.List;
6+
7+
/**
8+
* @author changleamazing
9+
* @date 2020/9/11 16:36 source: https://leetcode-cn.com/problems/combination-sum/
10+
**/
11+
public class Solution {
12+
13+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
14+
if(candidates.length == 0){
15+
return null;
16+
}
17+
Arrays.sort(candidates);
18+
List<List<Integer>> res = new ArrayList<>();
19+
Deque<Integer> tempList = new LinkedList<>();
20+
backtrace(candidates,0,target,tempList,res);
21+
return res;
22+
}
23+
24+
private void backtrace(int[] candidates,int begin,int target,Deque<Integer> tempQueue,List<List<Integer>> res){
25+
if(target == 0){
26+
res.add(new ArrayList<>(tempQueue));
27+
return;
28+
}
29+
for(int i = begin;i < candidates.length ;i++){
30+
if(target < candidates[i]){
31+
break;
32+
}
33+
tempQueue.add(candidates[i]);
34+
backtrace(candidates, i, target - candidates[i], tempQueue, res);
35+
tempQueue.removeLast();
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)