/*
Given an array: [1,2] and a target: 4
Find the solution set that adds up to the target
in this case:
[1,1,1,1]
[1,1,2]
[2,2]
*/
import "sort"
func combinationSum(candidates []int, target int) [][]int {
sort.Ints(candidates)
return combine(0, target, []int{}, candidates)
}
func combine(sum int, target int, curComb []int, candidates []int) [][]int {
var tmp [][]int
var result [][]int
if sum == target {
fmt.Println(curComb)
return [][]int{curComb}
} else if sum < target {
for i,v := range candidates {
tmp = combine(sum+v, target, append(curComb, v), candidates[i:])
result = append(result,tmp...)
}
}
return result
}
これはLeetcodeの問題で、私はそれを解決するために再帰を使用します。組み合わせの合計
18行目では、合計がターゲットと等しい場合にすべての場合を出力します。
[1,1,1,1]
[1,1,2]
[2,2]
そして、それは私が欲しいの答えです: 出力されます! しかし、なぜ最終的な答え(二次元)である:
[[1,1,1,2],[1,1,2],[2,2]]
予想答えは:[1,1,1,1]、[1,1,2]、[2,2]
コード内の誤りを見つけてください。御時間ありがとうございます。