当前位置:网站首页>LeetCode_回溯_中等_40.组合总和 II
LeetCode_回溯_中等_40.组合总和 II
2022-07-26 19:08:00 【小城老街】
1.题目
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次 。
注意:解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combination-sum-ii
2.思路
(1)回溯
本题与LeetCode_回溯算法_中等_39.组合总和这题十分类似,只不过本题的每个数字在每个组合中只能使用一次,所以在进行回溯的过程中需要进行对应的剪枝操作。
3.代码实现(Java)
//思路1————回溯
class Solution {
//res用于保存最终结果
List<List<Integer>> res = new ArrayList<>();
//track用于记录回溯的路径
ArrayList<Integer> track = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
if (candidates.length == 0) {
return res;
}
//先排序,以便让相等的元素排在一起,方便后续的剪枝操作
Arrays.sort(candidates);
backtrack(candidates, 0, target, 0);
return res;
}
public void backtrack(int[] candidates, int start, int target, int sum) {
if (sum == target) {
//找到目标组合,将其保存到 res 中
res.add(new ArrayList<>(track));
return;
}
if (sum > target) {
//组合元素之和超过target,直接结束
return;
}
//回溯算法框架
for (int i = start; i < candidates.length; i++) {
//剪枝操作,值相同的树枝,只遍历第一条
if (i > start && candidates[i - 1] == candidates[i]) {
continue;
}
//做选择
sum += candidates[i];
track.add(candidates[i]);
backtrack(candidates, i + 1, target, sum);
//撤销选择
sum -= candidates[i];
track.remove(track.size() - 1);
}
}
}
边栏推荐
猜你喜欢

kvm虚拟化

网红辣条抓不住年轻人

金融机构导图

【Android】Kotlin 快速编译背后的黑科技,了解一下~

eadiness probe failed: calico/node is not ready: BIRD is not ready: Error querying BIRD: unable to c

企业数字化转型成大趋势,选对在线协作工具很重要

Leetcode daily practice - 88. Merge two ordered arrays

【ffmpeg】给视频文件添加时间戳 汇总

Excel-VBA 快速上手(十、提示框、可输入的弹出框)

go+mysql+redis+vue3简单聊室,第6弹:使用vue3和element-plus调用接口
随机推荐
Overview of canvas
网红辣条抓不住年轻人
客户案例|生学教育依托观测云打造可观测智慧教育新生态
[PHP] MySQL native PHP operation - Tianlong eight steps
[internship experience] date verification
【MySQL】 - 索引原理与使用
Detailed explanation of call function in solidity
How to adjust the abnormal win11 USB drive to normal?
高瓴加入的PRI,君联、华控、盛世、绿动等百家机构都杀进去了
SVN - 详细文档
Is it safe for CSCI qiniu school to open an account? What is qiniu for
Codeforces Round #810 (Div. 2)(A~C)
Scope in JS
浅析接口测试
2022/07/26 learning notes (day16) linked list and stack
Implementing DDD based on ABP -- domain logic and application logic
[internship experience] exception handling and URL result response data processing
Codeforces Round #810 (Div. 2)(A~C)
Collection of original IOS interview questions
Canvas graphics