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

Leetcode40 无重复组合之和

题目描述:

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。

思路分析

这个题是leetcode39的延续组合之和
若不考虑重复,一个简单的思路是递归+回溯,要考虑去重, 一种有效做法是先排序,相同元素在同一条递归路径下只被选取一次,这样可以实现有效剪枝

代码实现

class Solution {public List<List<Integer>> combinationSum2(int[] candidates, int target) {List<List<Integer>> bs=new ArrayList<List<Integer>>(); List<Integer> bp = new ArrayList<Integer>();Arrays.sort(candidates);dfs(bs,bp,0,target,candidates);//深度优先搜索return bs;}//Leetcode高票答案private static void dfs(List<List<Integer>> result, List<Integer> temp, int index, int target, int[] coins){//termination condition;if(target < 0){return ;    }if(target == 0){result.add(new ArrayList<>(temp));return;}for(int i = index; i < coins.length && target >= coins[i]; i++){//when i is bigger than index & still duplicates(位置i处元素值之前加入过) we continue;if(i > index && coins[i] == coins[i-1]){continue;    }//有效避免重复 a a .. 与 a .. 情况重复出现(a代表当前要添加的元素)temp.add(coins[i]);dfs(result, temp, i + 1, target - coins[i], coins); // we cannot reuse it;temp.remove(temp.size()-1);}        }
}
http://www.lryc.cn/news/386189.html

相关文章:

  • 详解MATLAB中处理日期和时间的函数
  • Java养老护理助浴陪诊小程序APP源码
  • go的singleFlight学习
  • 高电压技术-冲击高压发生器MATLAB仿真
  • 【STM32】SysTick系统滴答定时器
  • 编码遵循五大设计原则创建出更加健壮、可维护和可扩展的软件系统
  • 记录一个问题
  • ONLYOFFICE 8.1版本桌面编辑器测评:重塑办公效率的巅峰之作
  • 【shell脚本速成】python安装脚本
  • Redis报错:MISCONF Redis is configured to save RDB snapshots
  • 关于使用绿联 USB-A转RJ45 2.5G网卡提速的解决问题
  • Qt: QPushButton 按钮实现 上图标下文字
  • 使用阿里云效API操作流水线
  • 使用命令行创建uniapp+TS项目,使用vscode编辑器
  • ABC355 Bingo2
  • Spring+Vue项目部署
  • 【uml期末复习】统一建模语言大纲
  • Linux高级IO
  • go-admin-ui开源后台管理系统华为云部署
  • 点云入门知识
  • HTML静态网页成品作业(HTML+CSS+JS)——家乡莆田介绍网页(5个页面)
  • #### grpc比http性能高的原因 ####
  • 微软Edge浏览器搜索引擎切换全攻略
  • <Linux> 实现命名管道多进程任务派发
  • BigInteger 和 BigDecimal(java)
  • Linux 进程间通讯
  • 数据分析三剑客-Matplotlib
  • FastAPI-Body、Field
  • 软件设计师笔记-操作系统知识(二)
  • 鸿蒙UI开发快速入门 —— part12: 渲染控制