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

组合求和2

题目描述:

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Example 1:

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

Example 2:

Input: candidates = [2,5,2,1,2], target = 5
Output: 
[
[1,2,2],
[5]
]

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

求解思路:

使用回溯(backtrack)算法。首先将原数组candidates按照取值从小到大排序,然后依次寻找可能求和等于目标值target的子数组。

构建一维动态数组combination存放可能成为候选的子数组,构建二维动态数组存放所有符合要求的子数组res。

回溯算法在子程序中完成,目标是依次遍历已排序的数组candidates中每个值,并判断当前值是否可以作为构成候选子数组的一份子。

(1)如果“目标值-当前求和=0”,也就是候选子数组的求和已经等于目标值,则结束当前回溯子过程,并把满足条件的候选子数组combination存入res中。

(2)依次遍历candidates数组时,当前值如果没有和前一个值重复,并且“目标值>= 当前求和+当前值”,则当前值有可能作为候选项。

从当前位置的下一个位置重新进入回溯子程序,直至找到满足条件的候选子数组,或者“目标值< 当前求和+当前值”,因为数组candidates已经从小到大排序,所以后续值也不可能满足条件了。

每个当前值在结束回溯子程序后,当前值都要从候选项子数组中弹出,也就是每个较小的值(当前求和+当前值<=目标值)都有可能在候选列表中,也有可能不在候选列表中,要兼顾两种情况。

代码:

vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {sort(candidates.begin(), candidates.end());vector<vector<int>> res;vector<int> combination;backtrack(res, combination, candidates, target, 0);return res;}void backtrack(vector<vector<int>> &res, vector<int> &combination, vector<int> &candidates, int target, int index){if (target ==0){res.push_back(combination);return;}for (int i = index; i<candidates.size()&& target>=candidates[i]; i++){if (i==index || candidates[i] != candidates[i-1]) {// not the same combination againcombination.push_back(candidates[i]);backtrack(res, combination, candidates, target-candidates[i], i+1);combination.pop_back();}}}

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

相关文章:

  • Apple Maps现在可在Firefox和Mac版Edge浏览器中使用
  • 基于嵌入式Linux的数据库
  • C# 使用LINQ找出一个子字符串在另一个字符串中出现的所有位置
  • YOLOv8添加MobileViTv3模块(代码+free)
  • 从概念到落地:全面解析DApp项目开发的核心要素与未来趋势
  • 仓颉编程入门 -- 泛型概述 , 如何定义泛型函数
  • SOC估算方法之(OCV-SOC+安时积分法)
  • 指针(下)
  • C# 浅谈IEnumerable
  • mmdebstrap:创建 Debian 系统 chroot 环境的利器 ️
  • 【Linux SQLite数据库】一、SQLite交叉编译与移植
  • 每天写两道(数组篇)移除元素、
  • Unity 使用 NewtonSoft Json插件报错
  • k8s 部署 Mysqld_exporter 以及添加告警规则
  • 基于STM32开发的智能农业环境监测系统
  • 【SQL】平均售价
  • 存储器与CPU的连接
  • unity--webgl 访问本地index.html
  • 慢慢欣赏DPDK RTE_MAX_ETHPORTS的定义
  • Java Nacos与Gateway的使用
  • 前端项目中的Server-sent Events(SSE)项目实践及其与websocket的区别
  • 《老俞闲话|唯爱和热情不可辜负》读后感
  • C语言 ——— 在杨氏矩阵中查找具体的某个数
  • DAI-Net: 基于对偶自适应交互网络的药物推荐算法
  • haproxy高级功能及配置
  • 【前端】NodeJS:记账本案例优化(MongoDB数据库)
  • Padding Mask;Sequence Mask;为什么如果没有适当的掩码机制,解码器在生成某个位置的输出时,可能会“看到”并错误地利用该位置之后的信息
  • 派森学长带你学python—字典
  • 如何设置 Visual Studio Code 的滚轮缩放功能
  • Python模拟退火算法