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

40. 组合总和 II - 力扣(LeetCode)

题目描述
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。

输入示例

candidates = [10,1,2,7,6,1,5], target = 8,

输出示例

[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

解题代码

class Solution {List<List<Integer>> result = new ArrayList<>();Deque<Integer> path = new ArrayDeque<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);int n = candidates.length;boolean[] used = new boolean[n];backtrack(candidates, target, 0, 0, used);return result;}public void backtrack(int[] candidates, int targetSum, int sum, int begin, boolean[] used) {if(sum > targetSum) {return;}if(sum == targetSum) {result.add(new ArrayList<Integer>(path));return;}for(int i = begin; i < candidates.length; i++) {if(i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false) {continue;}path.addLast(candidates[i]);sum += candidates[i];used[i] = true;backtrack(candidates, targetSum, sum, i+1, used);used[i] = false;sum -= candidates[i];path.removeLast();}}
}

在这里插入图片描述

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

相关文章:

  • 第15届蓝桥杯嵌入式省赛准备第二天总结笔记(使用STM32cubeMX创建hal库工程+按键输入)
  • 【论文阅读】One For All: Toward Training One Graph Model for All Classification Tasks
  • Python多线程爬虫——数据分析项目实现详解
  • unity全局音量管理/全局音量设置与音量设置界面(含静音功能)
  • C++ vector 数组转换、查找、最大最小值、排序、排行的几种用法
  • vmware 安装Rocky-9.3系统
  • C++提高编程——模板
  • 单线程、同步、异步、预解析、作用域、隐式全局变量、对象创建、new
  • 《设计模式的艺术》笔记 - 外观模式
  • sql 查询时间范围内的数据
  • TestNG中的@BeforeSuite注释
  • [学习笔记]刘知远团队大模型技术与交叉应用L3-Transformer_and_PLMs
  • 图像处理工具包Pillow的使用分享
  • python进程间通信——命名管道(Named Pipe、FIFO)
  • 03 OSPF 学习大纲
  • HJ7 取近似值【C语言】
  • php基础学习之常量
  • 2024最新面试经验分享
  • 《WebKit 技术内幕》之八(1):硬件加速机制
  • 子表单扫码录入,显著节省填写时间
  • 【Redis】Ubuntu安装配置
  • idea远程服务调试
  • Google Colab运行Pytorch项目
  • Android Studi安卓读写NDEF智能海报源码
  • Demo: 实现PDF加水印以及自定义水印样式
  • 每日OJ题_算法_二分查找①_力扣704. 二分查找
  • 【Python】--- 基础语法(1)
  • 详解gorm中DB对象的clone属性
  • 数据库(MySQL库表操作)
  • 内网穿透的应用-如何使用Docker部署Redis数据库并结合内网穿透工具实现公网远程访问