40-组合总和II

40-组合总和II

力扣40

https://leetcode-cn.com/problems/combination-sum-ii/

无脑套回溯模板就vans了

这题能评中等,大概率是因为去重的方式吧

题目比较简单,套模板五分钟就秒杀了吧,我就只贴leetcode模式代码了

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
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
backtrace(candidates, target, new ArrayList<>(), 0, 0);
return new ArrayList<>(res);
}

private Set<List<Integer>> res = new HashSet<>();
public void backtrace(int[] candidates, int target, List<Integer> path, int index, int sum){
//结束条件:路径中的和等于target
if (sum == target){
ArrayList<Integer> re = new ArrayList<>(path);
Collections.sort(re);
res.add(re);
return ;
}
for (int i = index; i < candidates.length; i++) {
//剪枝
if (sum > target) return ;
//做选择
sum += candidates[i];
path.add(candidates[i]);
//递归
backtrace(candidates, target, path, i + 1, sum);
//撤销
sum -= candidates[i];
path.remove(path.size() - 1);
}
}

以上方法,慢,但不是慢在set去重,博客曾经也提到过,Set去重效果比List.contains快了不止一个数量级,实际上,HashSet去重是O(1)的,因此是慢在结束条件的Collections.sort(re);

嗯,一开始就先对candidates排序,那么如果第二次加入的元素和前一次一样,那么就直接continue

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
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates); //一次性排序
backtrace2(candidates, target, new ArrayList<>(), 0, 0);
return new ArrayList<>(res);
}

private Set<List<Integer>> res = new HashSet<>();

public void backtrace2(int[] candidates, int target, List<Integer> path, int index, int sum){
//结束条件:路径中的和等于target
if (sum == target){
res.add(new ArrayList<>(path));
return ;
}
for (int i = index; i < candidates.length; i++) {
//剪枝
if (sum > target) return ;
//做选择
if(i > index && candidates[i] == candidates[i-1]) continue; //去重,第二次加入和前一次一样,则continue
sum += candidates[i];
path.add(candidates[i]);
//递归
backtrace2(candidates, target, path, i + 1, sum);
//撤销
sum -= candidates[i];
path.remove(path.size() - 1);
}
}

其他回溯的题目可以点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×