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
}
}
}
1.每个数只能使用一次:
func main() {
m := 13
k := []int{1, 2, 4, 7}
fmt.Print(solve(m, k))
}
func solve(m int, k []int) bool {
dfs(k, 0, 0, m)
return check
}
var check = false
var answer = []int{}
func dfs(k []int, cur int, sum int, target int) {
if sum == target {
fmt.Println("cur:", cur)
check = true
fmt.Println(answer)
return
}
if cur == len(k) { //结束位置
// fmt.Println(cur, sum)
if sum == target {
check = true
// fmt.Println(answer)
}
return
}
for i := cur; i < len(k); i++ {
if !check { //剪枝 已得到结果故直接退出
// fmt.Println("insert: ", k[i])
answer = append(answer, k[i])
dfs(k, cur+1, sum+k[i], target)
answer = answer[:len(answer)-1] //-1才会pop
// fmt.Println("pop", answer)
} else {
return
}
}
}