1 回答

TA贡献1880条经验 获得超4个赞
一种解决方案:
放
size = 1
使用递归(函数名称= getCombination在下面的代码片段中)来获取
size
输入数组中元素的所有组合。检查每个组合是否满足0 -> i的要求,如果是,则返回(完成)
如果没有任何组合匹配,则
size++
,然后转到步骤 2。
片段:
import (
"fmt"
)
var combination = []int{}
func GetCombination(src []int,size int, offset int) [][]int { // get all combinations for **size** elements in the elements of src array
result := [][]int{}
if size == 0 {
temp := make([]int, len(combination))
copy(temp, combination)
return append(result, temp)
}
for i:=offset; i<=len(src) - size; i++ {
combination = append(combination, src[i])
temp := GetCombination(src, size-1, i+1)
result = append(result, temp...)
combination = combination[:len(combination)-1]
}
return result[:]
}
func sum(items []int) int {
total := 0
for _, v := range items {
total += v
}
return total
}
func GetBestPair(items []int, target int) []int {
for i := 1; i < len(items)+1; i++ {
result := GetCombination(items, i, 0) // get all possible combinations for 1 -> len(items) elements of Array=items
// fmt.Println("Combinations for ", i, " elements:", result)
for j := 0; j < len(result); j++ {
total := sum(result[j])
if total < target {
continue
}
if total == target {
return result[j]
}
if total < target*10 {
return result[j]
}
}
}
return []int{}
}
func main () {
fmt.Println("Result", GetBestPair([]int{1, 3, 3, 61}, 6))
}
上述测试用例的输出
Combinations for 1 elements: [[1] [3] [3] [61]]
Combinations for 2 elements: [[1 3] [1 3] [1 61] [3 3] [3 61] [3 61]]
Result: [3 3]
- 1 回答
- 0 关注
- 153 浏览
添加回答
举报