当前位置:网站首页>LeetCode40-组合总数II
LeetCode40-组合总数II
2022-04-22 08:44:00 【西城风雨楼】
LeetCode40-组合总数II
一、题目描述

二、回溯树
组合是典型的求一个数列的子集问题,题目中的限制是找出的数列不能重复,那么这个也很简单,只需要将原序列进行升序排序即可,在回溯树横向扩展的时候(for循环),将重复的元素直接跳过即可(不进行递归,具体看代码)
三、组合总数II代码实现
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
// 这里必须要先排序,因为要去重
Arrays.sort(candidates);
solve(candidates, target, res, new ArrayList<>(), 0, 0);
return res;
}
public void solve(int[] candidates, int target, List<List<Integer>> res, List<Integer> curRes, int startIndex, int curSum) {
if (curSum == target) {
// 需要进行记录
res.add(new ArrayList<>(curRes));
return;
}
if (curSum > target) {
return;
}
for (int i = startIndex; i < candidates.length; i++) {
if (curSum + candidates[i] > target) {
break;
}
// 从第一个之后,需要判断是否需要进行去重
if (i > startIndex) {
// 横向去重
if (candidates[i] == candidates[i - 1]) {
continue;
}
}
curSum += candidates[i];
curRes.add(candidates[i]);
solve(candidates, target, res, curRes, i + 1, curSum);
curSum -= candidates[i];
curRes.remove(curRes.size() - 1);
}
}
}
版权声明
本文为[西城风雨楼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/xichengfengyulou/article/details/124332149
边栏推荐
- 824. 山羊拉丁文(模拟)
- The request client is not a secure context and the resource is in more-private address ...
- 【ValueError: math domain error】
- MySQL进阶之视图
- 【谈思生物直播课】——湖景生物王子元博士关于基因治疗乙肝的探索
- 开源,不只 coding
- Neo4j:Merge【不存在则创建,已存在可修改】
- Cmake使用基础知识一之基础语法
- Numpy notes (vstack, random.permutation, empty_like, empty, diff, random.choice, random.random, ISIN)
- Realize the "gradual display of font" program
猜你喜欢

On the difference between local variables and global variables

Examples of cmake basic knowledge II: single file, multiple files, dynamic and static library and use

花书《深度学习》与代码实现:01 线性代数:基本概念+代码实现基本运算

运维数据该如何防泄露

mysql用source命令导入sql出现报错 觉得应该是编码问题 不知道该怎么解决

Playing with kubernetes - Basic Concepts

IDEA连接成功H2数据库后什么子文件都没有

Learning objectives and general contents of C language

Breakthroughs and new development opportunities of smart watches

Baby naming artifact applet source code_ Support multiple traffic master modes
随机推荐
Advanced view of MySQL
【系统分析师之路】2020年下系统分析师案例分析真题
2022 R1 quick opening pressure vessel operation exercises and online simulation examination
瑞萨电子 MCU RT-Thread开发设计大赛
【谈思生物直播课】——湖景生物王子元博士关于基因治疗乙肝的探索
引水入城 洛谷P1514
Gym member management system requirements analysis document
ThreadLocal actual combat
分隔链表(建两个空链表)
Leetcode0396. Rotation function (medium, iteration)
六个方法,可以让你在NFT交易中收益更多
LeetCode 1450 - 1453
LeetCode 283. 移动零(简单、数组)day12
2022 high voltage electrician test simulation 100 questions and answers
RHCSA第二天作业
Using stack to realize queue (double stack, input stack and output stack)
Flink流处理引擎系统学习(二)
Intersecting linked list (set, double pointer)
Flink流处理引擎系统学习(三)
2022年R1快开门式压力容器操作练习题及在线模拟考试
