算法训练营day23(补),回溯3

import (

"sort"

)

39. 组合总和

func combinationSum(candidates []int, target int) [][]int {

//存储全部集合

result := make([][]int, 0)

if len(candidates) == 0 {

return result

}

sort.Ints(candidates) //排序后面做剪枝

//存储单次集合

path := make([]int, 0)

var backtrace func(candidates []int, target int, startIndex int)

backtrace = func(candidates []int, target int, startIndex int) {

if target == 0 {

temp := make([]int, len(path))

copy(temp, path)

result = append(result, temp)

return

}

for i := startIndex; i < len(candidates); i++ {

if candidates[i] > target { //剪枝

break

}

path = append(path, candidates[i])

backtrace(candidates, target-candidates[i], i)

//回溯处理

path = path[:len(path)-1]

}

}

backtrace(candidates, target, 0)

return result

}

40. 组合总和 II

func combinationSum2(candidates []int, target int) [][]int {

//存储全部集合

result := make([][]int, 0)

if len(candidates) == 0 {

return result

}

sort.Ints(candidates) //排序后面做剪枝

//记录数组每一个元素是否使用过

user := make([]bool, len(candidates))

//存储单次集合

path := make([]int, 0)

var backtrace func(candidates []int, target int, startIndex int)

backtrace = func(candidates []int, target int, startIndex int) {

if target == 0 {

temp := make([]int, len(path))

copy(temp, path)

result = append(result, temp)

return

}

for i := startIndex; i < len(candidates); i++ {

if candidates[i] > target { //剪枝

break

}

if i > 0 && candidates[i] == candidates[i-1] && user[i-1] == false { //过滤重复

continue

}

path = append(path, candidates[i])

user[i] = true

backtrace(candidates, target-candidates[i], i+1)

//回溯处理

path = path[:len(path)-1]

user[i] = false

}

}

backtrace(candidates, target, 0)

return result

}

//判断是否是回文

func isPalindrome(s string) bool {

for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {

if s[i] != s[j] {

return false

}

}

return true

}

131. 分割回文串

func partition(s string) [][]string {

//存储全部集合

result := make([][]string, 0)

if len(s) == 0 {

return result

}

//存储单次集合

path := make([]string, 0)

var backtrace func(se string, startIndex int)

backtrace = func(se string, startIndex int) {

if startIndex == len(se) {

temp := make([]string, len(path))

copy(temp, path)

result = append(result, temp)

return

}

for i := startIndex; i < len(se); i++ {

//对字符串进行切割

str := se[startIndex : i+1]

if isPalindrome(str) {

path = append(path, str)

backtrace(se, i+1)

//回溯处理

path = path[:len(path)-1]

}

}

}

backtrace(s, 0)

return result

}

相关推荐
洛水水6 小时前
【力扣100题】18.随机链表的复制
算法·leetcode·链表
南宫萧幕6 小时前
规则基 EMS 仿真实战:SOC 区间划分与 Simulink 闭环建模全解
算法·matlab·控制
爱滑雪的码农6 小时前
Java基础十七:数据结构
数据结构
多加点辣也没关系6 小时前
数据结构与算法|第二十三章:高级数据结构
数据结构·算法
代钦塔拉7 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
孬甭_8 小时前
初识数据结构与算法
数据结构
hoiii1879 小时前
孤立森林 (Isolation Forest) 快速异常检测系统
算法
InfinteJustice9 小时前
踩坑分享C 语言文件操作全攻略:从基础读写到随机访问与缓冲区原理
c语言·开发语言·microsoft
码云数智-大飞9 小时前
滥用Lombok的@EqualsAndHashCode导致线上事故复盘
开发语言
yong99909 小时前
C# 实时查看硬件使用率(CPU 内存 硬盘 网络)
开发语言·网络·c#