Fetch the repository succeeded.
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础Go语言算法实战》源码
// ++++++++++++++++++++++++++++++++++++++++
// Author:廖显东(ShirDon)
// Blog:https://www.shirdon.com/
// Gitee:https://gitee.com/shirdonl/goAlgorithms.git
// Buy link :https://item.jd.com/14101229.html
// ++++++++++++++++++++++++++++++++++++++++
package main
import "fmt"
// 对整数列表执行详尽搜索以找到目标值
func exhaustiveSearch(numbers []int, target int) int {
// 遍历每个可能的数字组合
for i := 0; i < (1 << uint(len(numbers))); i++ {
sum := 0
// 检查当前组合的每一位
for j := 0; j < len(numbers); j++ {
if (i & (1 << uint(j))) != 0 {
sum += numbers[j]
}
}
// 如果总和与目标匹配,则返回组合
if sum == target {
return i
}
}
// 如果没有找到组合,返回-1
return -1
}
func main() {
numbers := []int{1, 3, 6, 8}
target := 7
result := exhaustiveSearch(numbers, target)
if result != -1 {
fmt.Printf("找到总计为: %d 的组合: %d\n", result, target)
} else {
fmt.Println("找不到组合")
}
}
//$ go run exhaustiveSearch.go
//找到总计为: 5 的组合: 7
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。