```
package main
import (
"fmt"
"sort"
)
var result [][]int = make([][]int, 0)
func main() {
candidates := []int{2, 3, 6, 7}
target := 14
combinationSum(candidates, target)
for i, e := range result {
fmt.Println(i, ":", e)
}
}
func combinationSum(candidates []int, target int) {
sort.Ints(candidates)
record := []int{}
recursion(candidates, target, record)
result = unique(result)
}
func recursion(candidates []int, target int, record []int) {
if len(candidates) == 0 {
if target == 0 {
fmt.Print(result, "=>")
result = append(result, record)
fmt.Println(result)
}
return
}
for _, e := range candidates {
middleTarget := target - e
middleIndex := seekIndex(candidates, middleTarget)
middleRecord := append(record, e)
recursion(candidates[0:middleIndex], middleTarget, middleRecord)
}
}
func seekIndex(candidates []int, middleTarget int) int {
for i, v := range candidates {
if middleTarget < v {
return i
}
}
return len(candidates)
}
func unique(src [][]int) [][]int {
tgt := make([][]int, 0)
for _, v := range src {
ok := true
for i := 0; i < len(v)-1; i++ {
if v[i] > v[i+1] {
ok = false
break
}
}
if ok {
tgt = append(tgt, v)
}
}
return tgt
}
```
打印结果:<br/>
[]=>**[[2 2 2 2 2 2 2]]** **(ps:1)**<br/>
**[[2 2 2 2 2 3 2]]**=>[[2 2 2 2 2 3 2] [2 2 2 2 3 3]] **(ps:2)**<br/>
[[2 2 2 2 2 3 2] [2 2 2 2 3 3]]=>[[2 2 2 2 2 3 2] [2 2 2 2 3 3] [2 2 2 2 6]]<br/>
......
看ps:1和ps:2,怎么从[... 2 2]变成了[... 3 2]呢???
有疑问加站长微信联系(非本文作者)