1 Star 0 Fork 0

catyMap/AlgorithmNote

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
canPartition.go 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
dogeMap 提交于 2021-07-03 18:11 +08:00 . 更新题库
package main
import (
"fmt"
"sort"
)
// 回溯递归+ 剪枝,依然超时,看来动态规划不只是回溯解空间的单纯剪枝,就背包问题来说还可以达到更好的优化程度
// 因为
func canPartition(nums []int) bool {
n := len(nums)
target := 0
for _, v := range nums {
target += v
}
if target%2 != 0 {
return false
}
sort.Ints(nums)
sum := 0
flag := false
visted := make(map[int]bool)
var backtrace func(idx int)
backtrace = func(idx int) {
if idx > n {
return
}
if visted[sum] {
return
}
visted[sum] = true
if sum == target/2 || flag {
flag = true
return
}
for i := idx; i < n; i++ {
sum += nums[i]
if visted[sum] || sum > target/2 {
sum -= nums[i]
continue
}
backtrace(i + 1)
sum -= nums[i]
}
}
backtrace(0)
return flag
}
func main() {
fmt.Println((canPartition([]int{1, 5, 11, 5})))
fmt.Println(canPartition([]int{1, 2, 3, 5}))
fmt.Println(canPartition([]int{100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 99, 97}))
fmt.Println(canPartition([]int{14, 9, 8, 4, 3, 2}))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助