from book:挑战程序设计竞赛
编辑工具:vscode
编辑语言:Go
思路:使用DFS(四层for循环低效且容易超时)
code:
package main
import "fmt"
func main() {
n := 3 //len(k)
m := 10
k := []int{1, 3, 5}
fmt.Print(solve(n, m, k))
}
func solve(n int, m int, k []int) bool {
dfs(k, 0, 0, m)
return check
}
var check = false
func dfs(k []int, cur int, sum int, target int) {
if cur == 4 { //始终是 取4次
fmt.Println(cur, sum)
if sum == target {
check = true
}
return
}
for i := 0; i < len(k); i++ {
if !check { //剪枝 已得到结果故直接退出
dfs(k, cur+1, sum+k[i], target)
} else {
return
}
}
}
?