当前位置: 首页 > news >正文

力扣:40. 组合总和 II

回溯:

1.先声明好大集合和小集合,在调用回溯函数,终止条件为sum==target,要进行剪枝操作减少遍历的次数,去重操作防止数组中有两个相同的值来组成的集合相同。

class Solution {List<List<Integer>> li1=new ArrayList<List<Integer>>();List<Integer> li2=new ArrayList<Integer>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {//接收计算总和int sum=0;//方便去重操作Arrays.sort(candidates);huisu(candidates,target,0,sum);return li1;}public void huisu(int[] candidates,int target,int Index,int sum){//终止条件if(sum==target ){li1.add(new ArrayList<>(li2));return ;}//遍历和剪枝操作for(int i=Index;i<candidates.length&&sum+candidates[i]<=target;i++){//去重操作if (i>Index&&candidates[i]==candidates[i-1]){continue;} //加入集合li2中li2.add(candidates[i]);sum+=candidates[i];//嵌套huisu(candidates,target,i+1,sum);//回溯操作sum-=li2.get(li2.size()-1);li2.removeLast();}}
}

http://www.lryc.cn/news/303301.html

相关文章:

  • Java设计模式——责任链模式
  • c++面试
  • [ansible] playbook运用
  • MSSQL运用
  • linux命令--pidof
  • 计算机视觉发展的方向和潜在机会
  • Java Web(六)--XML
  • 智慧城市的新宠儿:会“思考”的井盖
  • Linux限定网络和工具环境下时间同步
  • SQL Server查询计划(Query Plan)——文本查询计划
  • 2024年2月的TIOBE指数,go语言排名第8,JAVA趋势下降
  • 机器人十大前沿技术(2023-2024年)
  • Spring: MultipartFile和File的区别
  • ncnn之三(补充):window环境下vs2022安装ncnn+protobuf
  • 第五篇【传奇开心果系列】Python文本和语音相互转换库技术点案例示例:详细解读pyttsx3的`preprocess_text`函数文本预处理。
  • logback实践
  • 深入理解java虚拟机---自动内存管理
  • 粉笔规范词积累(文化发展)
  • 如何在Ubuntu部署Emlog,并将本地博客发布至公网可远程访问
  • Axios
  • 数据仓库选型建议
  • 每日一题——LeetCode1470.重新排列数组
  • 网络安全--网鼎杯2018漏洞复现(二次注入)
  • CSS篇--transform
  • 阿里云国际-在阿里云服务器上快速搭建幻兽帕鲁多人服务器
  • vite 快速搭建 Vue3.0项目
  • 深入理解Python爬虫的Response对象
  • centos7下docker的安装
  • Excel SUMPRODUCT函数用法(乘积求和,分组排序)
  • C#上位机与三菱PLC的通信08---开发自己的通讯库(A-1E版)