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

LeetCode-数组/回溯-No40组合总和II

题目:

        给定一个候选人编号的集合 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:

  • 在No39CombinationSum基础上,每次回溯从下一个位置开始。
  • 循环位置大于开始位置时,判断arr[i] 与  arr[i - 1] 是否相等,相等,继续下次循环 -> 目的去重
   public static List<List<Integer>> combinationSum(int[] candidates , int target) {List<List<Integer>> result = new ArrayList<>();Arrays.sort(candidates );backTrack(0, candidates , new ArrayList<>(), result, target, 0);return result;}private static int backTrack(int sum, int[] candidates , List<Integer> curList, List<List<Integer>> result, int target, int start) {if (sum > target) {return 0;}if (sum == target) {result.add(new ArrayList<>(curList));return 1;} else {for (int i = start; i < candidates .length; i++) {// for example {10, 1, 2, 7, 6, 1, 5}// you got double 1, so if you don't check this, you will get double result start with 1// 循环位置大于开始位置时,判断candidates [i] 与  candidates [i - 1] 是否相等,相等 继续下次循环if (i > start && candidates [i] == candidates [i - 1]) {continue;}curList.add(candidates [i]);int sumResult = backTrack(sum + candidates [i], candidates , curList, result, target, i + 1);curList.remove(curList.size() - 1);if (sumResult != -1) {break;}}}return -1;}

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

相关文章:

  • 直接调用 Java 线程的 run() 方法会发生什么?
  • 计算机毕业设计Thinkphp/Laravel学生考勤管理系统zyoqy
  • 3浏览器安全
  • 昇思25天学习打卡Day01
  • Python-爬虫 下载天涯论坛帖子
  • 创建github个人博客
  • 【五子棋game】
  • 从入门到精通:使用Python的Watchdog库监控文件系统的全面指南
  • Linux 进程管理指令
  • Java OA系统通知公告模块
  • 简约的服务器监控工具Ward
  • 新能源发电乙级资质所需办理标准
  • Elasticsearch:使用 Llamaindex 的 RAG 与 Elastic 和 Llama3
  • AcWing算法基础课笔记——高斯消元
  • 【JavaScript脚本宇宙】图形魔术:探索领先的图像处理库及其独特功能
  • Nemotron-4
  • 【神经网络】神经元的基本结构和训练过程
  • 第28课 绘制原理图——绘制导线
  • NLP 相关知识
  • Java中的设计模式:实战案例分享
  • 并发编程理论基础——合适的线程数量和安全的局部变量(十)
  • Python使用抽象工厂模式和策略模式的组合实现生成指定长度的随机数
  • python-17-零基础自学python-
  • Web应用和Tomcat的集成鉴权1-BasicAuthentication
  • 解决Linux下Java应用因内存不足而崩溃的问题
  • ardupilot开发 --- 视觉伺服 篇
  • KVM配置嵌套虚拟化
  • Springboot应用的信创适配-补充
  • 制图工具(14)导出图层字段属性信息表
  • 代码随想录——买股票的最佳时机Ⅱ(Leecode122)