4 Star 13 Fork 10

ShirDon-廖显东/零基础Go语言算法实战源码

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
exhaustiveSearch.go 1.14 KB
Copy Edit Raw Blame History
ShirDon-廖显东 authored 2024-04-22 14:56 +08:00 . first commit
// ++++++++++++++++++++++++++++++++++++++++
// 《零基础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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shirdonl/goAlgorithms.git
git@gitee.com:shirdonl/goAlgorithms.git
shirdonl
goAlgorithms
零基础Go语言算法实战源码
3e77a12194dd

Search