代码随想录算法训练营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://xiahunao.cn/news/2808612.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

【C++精简版回顾】12.友元函数

1.友元函数 1.class class MM { public:MM(int age,string name):age(age),name(name){}friend void print(MM mm); private:int age;string name;void print() {cout << age << "岁的" << name << "喜欢你" << endl;} }; f…

Redis如何修改key名称

点击上方蓝字关注我 近期出现过多次修改Redis中key名字的场景&#xff0c;本次简介一下如何修改Redis中key名称的方法。 1. 命令行方式修改在Redis中&#xff0c;可以使用rename命令来修改Key的名称。这个命令的基本语法如下&#xff1a; RENAME old_key new_key 在这里&#…

学习或从事鸿蒙开发工作,有学历要求吗?

目前安卓有2,000万的开发者。本科及以上学历占比为35%&#xff1b;iOS有2,400万开发者&#xff0c;本科及以上学历占比为40% 绝大多数的前端开发者都是大专及以下学历&#xff0c;在2023年华为开发者大会上余承东透露华为的开发者目前有200万&#xff0c;但鸿蒙开发者统计的数据…

【GAD】基于邻域重建的图异常检测

GAD-NR: Graph Anomaly Detection via Neighborhood Reconstruction 摘要contributionsMethodologyGAE via Neighborhood Reconstruction邻域重建整体重建损失 实验 WSDM2024Link Code | 摘要 图异常检测&#xff08;GAD&#xff09;是一种用于识别图中异常节点的技术&#x…

istio系列教程

istio学习记录——安装https://suxueit.com/article_detail/otVbfI0BWZdDRfKqvP3Gistio学习记录——体验bookinfo及可视化观测https://suxueit.com/article_detail/o9VdfI0BWZdDRfKqlv0r istio学习记录——kiali介绍https://suxueit.com/article_detail/pNVbfY0BWZdDRfKqX_0K …

在使用nginx的时候快速测试配置文件,并重新启动

小技巧 Nginx修改配置文件后需要重新启动&#xff0c;常规操作是启动在任务管理器中关闭程序然后再次双击nginx.exe启动&#xff0c;但是使用命令行就可以快速的完成操作。 将cmd路径切换到nginx的安装路径 修改完成配置文件后 使用 nginx -t校验nginx 的配置文件是否出错 …

力扣随笔之颜色分类(中等75)

思路&#xff1a;定义两个指针划分left&#xff0c;right划分三个区域left左边是红色区域&#xff0c;right右边是蓝色区域&#xff0c;left和right之间是白色区域&#xff1b;定义一个遍历指针遍历整个数组&#xff0c;遇到红色与left所指位置数字交换&#xff0c;并将left自加…

考研408深度分析+全年规划

408确实很难&#xff0c;他的难分两方面 一方面是408本身的复习难度&#xff0c;我们都知道&#xff0c;408的考察科目有四科&#xff0c;分别是数据结构&#xff0c;计算机组成原理&#xff0c;操作系统和计算机网络。大家回想一下自己在大学本科时候学习这些专业课的难度&am…

快速排序C语言实现程序

快速排序 快速排序算法一种最常见的排序算法&#xff0c;其核心思想就是 分治 &#xff0c;具体的&#xff1a;1&#xff09; 选定一个基准数&#xff1b;2&#xff09; 分区&#xff0c;将所有大于基准数的数据分为一区&#xff0c;将所有小于等于基准数的数据分为一区&#x…

Redis主从、哨兵、Redis Cluster集群架构

Redis主从、哨兵、Redis Cluster集群架构 Redis主从架构 Redis主从架构搭建 主从搭建的问题 如果同步数据失败&#xff0c;查看log日志报错无法连接&#xff0c;检查是否端口未开放出现”Error reply to PING from master:...“日志&#xff0c;修改参数protected-mode no …

《乱弹篇(十八)天灾人祸》

昨天午后笔者发表《贵州山火频发&#xff0c;令人扼腕痛惜》一文后&#xff0c;昨晚和今日上午又见社交网站上媒体发表的最新消息报道《南京一小区火灾已造成15死44伤&#xff0c;市长鞠躬道歉》《南京“223”火灾15死44伤&#xff1a;为啥1楼起火烧到了30层&#xff1f;除了电…

C/C++文件操作

一、文本文件操作 1、写文件操作 代码 #include<fstream> #include<iostream>int main() {ofstream outfile("Student.txt", ios::out);if (!outfile) {cout << "文件写入失败" << endl;exit(0); //程序终止}cout << &qu…

k8s-kubeapps部署 20

部署kubeapps应用&#xff0c;为Helm提供web UI界面管理&#xff1a; 下载最新版本的kubeapps并修改其values.yaml文件 下载并拉取所需镜像&#xff1a; 部署应用 添加解析 修改svc暴露方式为LoadBalancer 得到分配地址 访问http://192.168.182.102 授权并获取token 1.24前的…

LeetCode 1038.从二叉搜索树到更大和树

给定一个二叉搜索树 root (BST)&#xff0c;请将它的每个节点的值替换成树中大于或者等于该节点值的所有节点值之和。 提醒一下&#xff0c; 二叉搜索树 满足下列约束条件&#xff1a; 节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左…

Orange3数据预处理(列选择组件)数据角色及类型描述

在Orange3的文件组件中&#xff0c;datetime、categorical、numeric以及text代表不同种类的数据类型&#xff0c;具体如下&#xff1a; datetime&#xff1a;代表日期和时间类型的数据。通常用于时间序列分析、生存分析和其他需要考虑时间因素的机器学习任务中。例如&#xff0…

【Linux】部署前后端分离项目---(Nginx自启,负载均衡)

目录 前言 一 Nginx&#xff08;自启动&#xff09; 2.1 Nginx的安装 2.2 设置自启动Nginx 二 Nginx负载均衡tomcat 2.1 准备两个tomcat 2.1.1 复制tomcat 2.1.2 修改server.xml文件 2.1.3 开放端口 2.2 Nginx配置 2.2.1 修改nginx.conf文件 2.2.2 重启Nginx服务 2…

【动态规划题目讲解】AGC026D - Histogram Coloring

[ A G C 026 D ] H i s t o g r a m C o l o r i n g \mathrm{[AGC026D] Histogram\ Coloring} [AGC026D]Histogram Coloring D e s c r i p t i o n \mathrm{Description} Description 给定 N N N 列的网格&#xff0c;每列高为 h i h_i hi​&#xff0c;将每个格子染色成红…

鸿蒙开发【WebGL】简单了解

WebGL的全称为Web Graphic Library(网页图形库)&#xff0c;主要用于交互式渲染2D图形和3D图形。目前HarmonyOS中使用的WebGL是基于OpenGL裁剪的OpenGL ES&#xff0c;可以在HTML5的canvas元素对象中使用&#xff0c;无需使用插件&#xff0c;支持跨平台。WebGL程序是由JavaScr…

什么是抖音视频下载软件|视频批量下载|爬虫工具

抖音视频抓取软件是一款方便用户获取抖音平台上视频内容的工具。它具备以下主要功能&#xff1a; 批量视频提取&#xff1a;用户可以输入关键词&#xff0c;软件将自动搜索抖音平台上与关键词相关的视频&#xff0c;并将它们列出供用户选择和下载。用户可以随时停止搜索和下载过…

【数电】一文带你轻松搞定奇偶校验原理与规则(案例演示)

前言 大家好吖&#xff0c;欢迎来到 YY 滴单片机系列 &#xff0c;热烈欢迎&#xff01; 本章主要内容面向接触过单片机的老铁 主要内容含&#xff1a; 欢迎订阅 YY滴C专栏&#xff01;更多干货持续更新&#xff01;以下是传送门&#xff01; YY的《C》专栏YY的《C11》专栏YY的…