# 求助：递归下，slice发生了什么？？？

tryfinally · · 905 次点击 · 开始浏览    置顶

``` 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]呢？？？

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传