代码随想录算法训练营day27|39. 组合总和、40.组合总和II

39. 组合总和 

如下树形结构如下:

39.组合总和

选取第二个数字5之后,剩下的数字要从5、3中取数了,不能再取2了,负责组合就重复了,注意这一点,自己做的时候没想明白这一点

如果是一个集合来求组合的话,就需要startIndex,例如:77.组合 (opens new window),216.组合总和III

如果是多个集合取组合,各个集合之间相互不影响,那么就不用startIndex,例如:17.电话号码的字母组合

代码如下:

class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:result= []path = []self.backtracking(candidates,0,target,path,result)return resultdef backtracking(self,candidates,startIndex,target,path,result):if sum(path) > target:returnif sum(path) == target:result.append(path[:])returnfor i in range(startIndex,len(candidates)):path.append(candidates[i])self.backtracking(candidates,i,target,path,result)path.pop()

剪枝优化

class Solution:def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:result= []path = []candidates.sort() #列表要排序self.backtracking(candidates,0,target,path,result)return resultdef backtracking(self,candidates,startIndex,target,path,result):if sum(path) == target:result.append(path[:])returnfor i in range(startIndex,len(candidates)): #剪枝优化都是在for循环中做优化if sum(path) > target: #如果组合的和比目标值要大就跳出循环break path.append(candidates[i])self.backtracking(candidates,i,target,path,result)path.pop()

 40.组合总和II 

自己做法:

考虑到把数组排序了,那么在收集数组的时候,也是按照排序来的,所以可以直接return结果:

class Solution:def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:result = []candidates.sort()self.backtrack(candidates,target,0,[],result)return resultdef backtrack(self,candidates,target,startIndex,path,result):if path in result: #直接returnreturnif sum(path) == target:result.append(path[:])returnfor i in range(startIndex,len(candidates)):if sum(path) > target:continuepath.append(candidates[i])self.backtrack(candidates,target,i+1,path,result)path.pop()        

代码随想录:

class Solution:def backtracking(self, candidates, target, total, startIndex, path, result):if total == target:result.append(path[:])returnfor i in range(startIndex, len(candidates)):if i > startIndex and candidates[i] == candidates[i - 1]:continueif total + candidates[i] > target:breaktotal += candidates[i]path.append(candidates[i])self.backtracking(candidates, target, total, i + 1, path, result)total -= candidates[i]path.pop()def combinationSum2(self, candidates, target):result = []candidates.sort()self.backtracking(candidates, target, 0, 0, [], result)return result

使用used:

选择过程树形结构如图所示:

40.组合总和II

class Solution:def backtracking(self, candidates, target, total, startIndex, used, path, result):if total == target:result.append(path[:])returnfor i in range(startIndex, len(candidates)):# 对于相同的数字,只选择第一个未被使用的数字,跳过其他相同数字if i > startIndex and candidates[i] == candidates[i - 1] and not used[i - 1]:continueif total + candidates[i] > target:breaktotal += candidates[i]path.append(candidates[i])used[i] = Trueself.backtracking(candidates, target, total, i + 1, used, path, result)used[i] = Falsetotal -= candidates[i]path.pop()def combinationSum2(self, candidates, target):used = [False] * len(candidates)result = []candidates.sort()self.backtracking(candidates, target, 0, 0, used, [], result)return result

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/702329.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

找游戏 - 华为OD统一考试(C卷)

OD统一考试(C卷) 分值: 200分 题解: Java / Python / C 题目描述 小扇和小船今天又玩起来了数字游戏, 小船给小扇一个正整数 n(1 ≤ n ≤ 1e9),小扇需要找到一个比 n 大的数字 m&a…

算法 给定N个整数序列{A1,A2,....,An}求所有子序列之和的最大值

今天 &#xff0c; 开始学习算法 &#xff0c; 以这个列子解释复杂度对算法的影响 #include <stdio.h> int main() { int i 0; int arr[8] { -1,2,-3,4,-4,7,8,9 }; int j 0; int k 0; int sum 0; int max_sum 0; for( i 0 ; i < …

c#中使用devexpress gridcontrol 获取排序后的gridview数据

//获取排序后的DataTable DataTable _dt lvwItems.GridControl.DataSource as DataTable; DataTable table _dt.Clone(); for (int i 0; i < lvwItems.RowCount; i) { if (lvwItems.IsGroupRow(i)) …

如何增加层次厚度?

Q 老师&#xff0c;我在做一个斧头武器&#xff0c;如何在平面上增加厚度和层次呢&#xff1f; A 选中这几个线&#xff0c;点连接就会出现中线&#xff0c;把中线稍作调整即可~

glTF 添加数据属性(extras)

使用3D 模型作为可视化界面的一个关键是要能够在3D模型中添加额外的数据属性&#xff0c;利用这些数据属性能够与后台的信息模型建立对应关系&#xff0c;例如后台信息模型是opcua 信息模型的话&#xff0c;在3D模型中要能够包含OPC UA 的NodeId&#xff0c;BrowserName 等基本…

wcf 简单实践 数据绑定 数据校验

1.概要 1.1 说明 数据校验&#xff0c;如果数据不合适&#xff0c;有提示。 1.2 要点 class User : IDataErrorInfothis.DataContext user;<Window.Resources><Setter Property"ToolTip" Value"{Binding RelativeSource{RelativeSource Self},Pat…

3.WEB渗透测试-前置基础知识-快速搭建渗透环境(上)

上一个内容&#xff1a;2.WEB渗透测试-前置基础知识-web基础知识和操作系统-CSDN博客 1.安装虚拟机系统 linux Kali官网下载地址&#xff1a; https://www.kali.org/get-kali/#kali-bare-metal Centos官网下载地址&#xff1a; https://www.centos.org/download/ Deepin官网下…

外包干了3个月,技术倒退1年。。。

先说情况&#xff0c;大专毕业&#xff0c;18年通过校招进入湖南某软件公司&#xff0c;干了接近6年的功能测试&#xff0c;今年年初&#xff0c;感觉自己不能够在这样下去了&#xff0c;长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了四年的功能测试&#xf…

5555555官方v给

☞ 通用计算机启动过程 1️⃣一个基础固件&#xff1a;BIOS 一个基础固件&#xff1a;BIOS→基本IO系统&#xff0c;它提供以下功能&#xff1a; 上电后自检功能 Power-On Self-Test&#xff0c;即POST&#xff1a;上电后&#xff0c;识别硬件配置并对其进行自检&#xff0c…

AES 和 MD5

当涉及到数据安全时&#xff0c;常用的加密算法包括 AES 和 MD5。以下是对它们的简要介绍&#xff1a; AES&#xff08;Advanced Encryption Standard&#xff09;&#xff1a;AES 是一种对称加密算法&#xff0c;被广泛应用于保护数据的传输和存储安全。AES 加密使用相同的密钥…

记录realsense包编译出错的问题

我是ros1...但是下载的包好像适用于ros2 合适的下载地址&#xff1a; ROS1 打开图中所选地址 https://github.com/IntelRealSense/realsense-ros/blob/ros1-legacy/README.md#installation-instructions 版本选择ros1 下载到对应位置即可

牛客周赛 Round 34 解题报告 | 珂学家 | 构造思维 + 置换环

前言 整体评价 好绝望的牛客周赛&#xff0c;彻底暴露了CF菜菜的本质&#xff0c;F题没思路&#xff0c;G题用置换环骗了50%, 这大概是唯一的亮点了。 A. 小红的字符串生成 思路: 枚举 a,b两字符在相等情况下比较特殊 a, b input().split() if a b:print (2)print (a)pri…

【监控】grafana图表使用快速上手

目录 1.前言 2.连接 3.图表 4.job和path 5.总结 1.前言 上一篇文章中&#xff0c;我们使用spring actuatorPrometheusgrafana实现了对一个spring boot应用的可视化监控。 【监控】Spring BootPrometheusGrafana实现可视化监控-CSDN博客 其中对grafana只是打开了一下&am…

【数据结构与算法】(22)高级数据结构与算法设计之 Divide and Conquer 分治法 代码示例与详细讲解

目录 4.4 Divide and Conquer1) 概述二分查找快速排序归并排序合并K个排序链表 - LeetCode 23对比动态规划 2) 快速选择算法数组中第k个最大元素-Leetcode 215数组中位数 3) 快速幂-Leetcode 504) 平方根整数部分-Leetcode 695) 至少k个重复字符的最长子串-Leetcode 395 4.4 Di…

云原生之API网关Traefik

1. 前言 说到web服务的开源网关&#xff0c;我首先想到的是Nginx&#xff0c;最早使用的就是它&#xff0c;现在都还在使用它。系统上线了Docker Swarm集群之后&#xff0c;不继续使用Nginx直接做Docker服务的网关&#xff0c;是因为Nginx毕竟比Docker Swarm出现的早&#xff0…

简单实现文字滚动效果-CSS版本

先看看效果 话不多说直接上代码 <template><div class"main"><div class"scroll-region"><div class"swiper-scroll-content"><span class"list-btn" v-for"(item, index) in overviewList" :…

【基于Ubuntu20.04的Autoware.universe安装过程】方案二:双系统 | 详细记录 | 全过程图文 by.Akaxi

目录 一、Autoware.universe背景 Part-1&#xff1a;安装双系统教程 二、查看Windows引导方式 三、制作安装盘 四、设置电脑配置 1.关闭bitlocker 2.压缩硬盘分区 3.关闭Secure Boot 4.关闭intel RST 5.BIOS设置U盘引导 五、安装Ubuntu20.04 1.ventoy引导 2.安装配…

07 Redis之持久化(RDB(Redis DataBase) + 写时复制 + AOF(Append Only File)+混合持久化)

4 Redis持久化 Redis 是一个内存数据库&#xff0c;然而内存中的数据是不持久的&#xff0c;若主机宕机或 Redis 关机重启&#xff0c;则内存中的数据全部丢失。 当然&#xff0c;这是不允许的。Redis 具有持久化功能&#xff0c;其会按照设置以快照或操作日志的形式将数据持…

双重检查锁定与延迟初始化

双重检验锁&#xff1a;多线程下的单例模式。 懒加载模式&#xff1a;延迟初始化。

unity学习(39)——创建(create)角色脚本(panel)——静态(static)

1.发现一个非常实用的功能&#xff0c;点击unity中console的输出项&#xff0c;可以直接跳转到vs的代码页&#xff01; 2.static类&#xff08;变量&#xff09;有三个特点&#xff1a; &#xff08;1&#xff09;独一份&#xff08;2&#xff09;无法实例化。&#xff08;3&…