0%

LeetCode-39

题目

结果

代码

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
class Solution {
List<List<Integer>> ans = new LinkedList<>();

public List<List<Integer>> combinationSum(int[] candidates, int target) {
// 递归
search(candidates, target, new LinkedList<Integer>());
// 排序以便去重
ans.forEach(integers -> integers.sort(Integer::compareTo));
// 去重并返回
return ans.stream().distinct().collect(Collectors.toList());
}

private void search(int[] candidates, int target, List<Integer> tmp) {
// 递归终止条件
if (target < 0) {
return;
}
if (target == 0) {
ans.add(new LinkedList<>(tmp));
}

for (int num : candidates) {
List<Integer> integerList = new LinkedList<>(tmp);
integerList.add(num);
search(candidates, target - num, integerList);
}
}
}

复杂度

时间复杂度:idk

空间复杂度:idk