Skip to content

Commit d563ded

Browse files
committed
0040. Combination Sum II V1.0
1 parent 967ac29 commit d563ded

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
import java.util.stream.Collectors;
7+
8+
/**
9+
* @author changleamazing
10+
* @date 2020/9/11 17:06 source: https://leetcode-cn.com/problems/combination-sum-ii/
11+
**/
12+
public class Solution {
13+
public List<List<Integer>> combinationSum2(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+
if (i > begin && candidates[i] == candidates[i - 1]) {
34+
continue;
35+
}
36+
37+
tempQueue.add(candidates[i]);
38+
backtrace(candidates, i + 1, target - candidates[i], tempQueue, res);
39+
tempQueue.removeLast();
40+
}
41+
}
42+
43+
public static void main(String[] args) {
44+
int[] candidates = {4, 4, 2, 1, 4, 2, 2, 1, 3};
45+
Solution solution = new Solution();
46+
solution.combinationSum2(candidates, 6);
47+
}
48+
}

0 commit comments

Comments
 (0)