Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II)
2024-10-10 20:55:06
Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II)
给定一个数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用一次。
说明:
- 所有数字(包括目标数)都是正整数。
- 解集不能包含重复的组合。
示例 1:
输入: candidates =[10,1,2,7,6,1,5]
, target =8
,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
] 分析:跟上一题(Leetcode.39)类似,区别在于这题每个数字只能用一次。还是同样的思想(回溯法),
大于target的直接跳过,先排序。 回溯法 -> 举例
candidates =[10,1,2,7,6,1,5]
, target =8 , 排序后candidates = [1,1,2,5,6,7,10]
首先,入口是dfs(index=0)
选第一个1,这里我们标记为step1,
接着继续选取第二个1,标记为step2,
继续选2,step3,
选5,标记为step4,
此时已超出target=8(此时为9),故大于了target,根据代码return到上一步,返回到step4,不选5,选6
超出,退回,不选6,选7,超出,退回,选10,超出,退回。(我的AC代码里在后面还是循环了,所以浪费了很多时间,可以发现大于的就直接返回,不进入下一步了) 以此类推。因此第一个产生出来的答案应该是 1 2 5
AC代码:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates,target,0,target,new ArrayList<Integer>());
return ans;
} public void dfs(int[] candidates,int target,int index,int balance,ArrayList<Integer> list){
if(balance<0){
return;
}
if(balance==0){
if(!ans.contains(list)) ans.add(new ArrayList<Integer>(list));
return;
} if(index>=candidates.length){
return;
}
int num = candidates[index]; list.add(num);
dfs(candidates,target,index+1,balance-num,list);
list.remove(list.size()-1);
dfs(candidates,target,index+1,balance,list); }
}
最新文章
- Windows下虚拟机安装Ubuntu15.10 Destop简易操作过程
- Apache问题处理服务器访问不了
- easyUI combobox 控件 使用
- HashMap源码阅读笔记(基于jdk1.8)
- 【非原创】IOS 验证文字是否是中文
- excle心得及部分应用案例
- August 3rd, 2016, Week 32nd, Wednesday
- 解决zabbix图中出现中文乱码问题 图中的中文会变成方块
- jquery闭包的使用
- centos7 php7 安装composer时Failed to decode zlib stream解决办法
- c++ 中关于int,unsigned int , short的关系与应用
- Bellman 算法
- Queue(队列)
- DLP底座(威创定制)
- JS菜单条智能定位效果
- RestServer 2.0 正式版发布
- pycharm远程debug(内网环境,跳板机)
- 技术的热门度曲线:GHC
- 在cef中使用自定义协议(scheme)
- vue Axios 封装与配置项