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 關注
- 148 瀏覽
添加回答
舉報