算法训练营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 candidatesi > target { //剪枝

break

}

path = append(path, candidatesi)

backtrace(candidates, target-candidatesi, 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 candidatesi > target { //剪枝

break

}

if i > 0 && candidatesi == candidatesi-1 && useri-1 == false { //过滤重复

continue

}

path = append(path, candidatesi)

useri = true

backtrace(candidates, target-candidatesi, i+1)

//回溯处理

path = path:len(path)-1

useri = 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 si != sj {

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 := sestartIndex : i+1

if isPalindrome(str) {

path = append(path, str)

backtrace(se, i+1)

//回溯处理

path = path:len(path)-1

}

}

}

backtrace(s, 0)

return result

}

相关推荐
不会就选b1 小时前
算法日常・每日刷题--<贪心>14
算法
mmmmath_34 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z4 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
君顾15 小时前
上海24小时自助健身房系统开发实战指南:从架构设计到落地部署
java·开发语言·健身房
醇氧5 小时前
MySQL 8.0 系统表损坏与引擎转换故障排查实战
数据结构·算法
大熊背6 小时前
《Color constancy by characterization of illumination chromaticity》之色度色域最大化算法(二)
算法·白平衡·色度·色温
香菜TTT6 小时前
大模型上下文协议(MCP):AI 应用的“USB-C”接口技术
开发语言·人工智能·经验分享
钓鱼的肝6 小时前
梳理(1-5)
c++·经验分享·笔记·算法·青少年编程
aramae6 小时前
模拟实现strlen()函数 (C语言)
c语言·开发语言·后端