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

刷题笔记day27-回溯算法3

39. 组合总和


var path []int
var tmp []int
var result [][]int// 还是需要去重复,题目中要求的是至少一个数字备选的数量不同。
// 所以需要剪枝操作,右边的要比左边的>=
func combinationSum(candidates []int, target int) [][]int {// 组合问题path = []int{}result = [][]int{}nfs(candidates, target, 0)return result
}func nfs(candidates []int, curr, startIndex int) bool {// 终止条件if curr == 0 {tmp = make([]int, len(path))copy(tmp, path)result = append(result, tmp)return true} else if curr < 0 {return false}for i := startIndex; i < len(candidates); i++ {// 去重:右边的比左边的大的情况,才继续,startIndexpath = append(path, candidates[i])// nfsnfs(candidates, curr-candidates[i], i)if len(path) > 0 {path = path[:len(path)-1]}}return true
}

40. 组合总和 II ⭐️⭐️⭐️

这个题很重点,
关键点:

  • 一个组内可以允许重复
  • 但是不同组,不可以是重复的

涉及到是同一层是否重复(就是不同组),还是某一个树枝是否重复(同一组内)。
所以这样,就很清晰了。
我们可以用一个 used 数组,如果used[i] = true,说明在一个同一个树枝上使用了。
// 去除相邻重复
// used[i-1] == true 说明,在同一树枝上使用了
// used[i-1] == false,说明,不是同一树枝,此时如果candidates[i] == candidates[i-1],
在这里插入图片描述


import "sort"var path []int
var result [][]intfunc combinationSum2(candidates []int, target int) [][]int {// 这个是给定一个数组了,在里面挑选。// 我的思路就是,先排序在递归// 还有一种情况,111435, 这个重复值,在第二次,就不应该再用了path = []int{}result = [][]int{}sort.Ints(candidates)used := make([]bool, len(candidates))nfs(candidates, 0, target, used)return result
}func nfs(candidates []int, startIndex, curr int, used []bool) {// 终止条件if (curr == 0) {result = append(result, append([]int{}, path...))return } else if (curr < 0) {return }// 循环for i := startIndex; i < len(candidates); i++ {// 去除相邻重复// used[i-1] == true 说明,在同一树枝上使用了// used[i-1] == false,说明,不是同一树枝,此时如果candidates[i] == candidates[i-1],// 那么就跳过if i > 0 && candidates[i] == candidates[i-1] && used[i-1] == false {continue}used[i] = truepath = append(path, candidates[i])nfs(candidates, i+1, curr-candidates[i], used)used[i] = false// 回溯if (len(path) > 0) {path = path[:len(path)-1]}}
}
http://www.lryc.cn/news/311851.html

相关文章:

  • 【项目】Boost 搜索引擎
  • vue3 (六)自定义指令
  • vite、mode如果为production打包后 .env.production 中 VITE_API_DOMAIN变量作为API地址吗
  • 静态时序分析:SDC约束命令set_fasle_path详解
  • 浅谈马尔科夫链蒙特卡罗方法(MCMC)算法的理解
  • 2403C++,C++20协程库
  • mybatis动态加载mapper.xml
  • 安卓类加载机制
  • FPGA高端项目:FPGA基于GS2971的SDI视频接收+HLS图像缩放+多路视频拼接,提供4套工程源码和技术支持
  • [计算机网络]--五种IO模型和select
  • 【力扣经典面试题】14. 最长公共前缀
  • Linux操作系统的vim常用命令和vim 键盘图
  • SpringCloudGateway工作原理与链路图
  • VUE2与VUE3之间的主要区别
  • CSS浮动实战,经典好文
  • 如何搭建Nacos集群
  • 未来已来!AI大模型引领科技革命
  • VBA如何记录单元格中字符内容和格式
  • 逻辑漏洞(pikachu)
  • 阿里云服务器2核4G多少钱?支持多少在线?并发数性能测试
  • 粘包与拆包
  • 基于QGIS的研究区域遥感影像裁切下载方法-以岳麓区为例
  • YOLOv8-Openvino-ByteTrack【CPU】
  • 【Linux命令】tload
  • Qt 通过pdfium将网络上的pdf显示为图片
  • C语言数据结构与算法——深度、广度优先搜索(DFS、BFS)
  • Golang Channel 详细原理和使用技巧
  • CSS的浮动属性,web前端开发工程师
  • Dubbo的集群容错方案
  • 两天学会微服务网关Gateway-Gateway路由规则