slice切片中出现了两个冒号

leetcode39的一个解答,其中solution = solution[:len(solution):len(solution)]这一句中出现了两个冒号,没明白第二个冒号的作用,求解答。

func combinationSum(candidates []int, target int) [][]int {
    result := [][]int{}

    sort.Ints(candidates)

    solution := []int{}

    cs(candidates, target, solution, &result)

    return result
}

func cs(candidates []int, target int, solution []int, result *[][]int) {
    if target == 0 {
        *result = append(*result, solution)
    }

    if len(candidates) == 0 {
        return
    }

    if target < candidates[0] {
        return
    }

    // 就是这一句
    solution = solution[:len(solution):len(solution)]

    cs(candidates, target - candidates[0], append(solution, candidates[0]), result)

    cs(candidates[1 : ], target, solution, result)
}

解答地址:https://github.com/aQuaYi/LeetCode-in-Go/tree/master/Algorithms/0039.combination-sum

已邀请:

h12 - https://h12.io/about

赞同来自: buscoop Taeja

用来设置cap。

"a[low : high : max] constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low. "

基础语法需参考spec:https://golang.org/ref/spec#Slice_types

wuhan

赞同来自: buscoop Taeja

a[x:y:z] 切片长度: y-x 切片容量:z-x

buscoop

赞同来自:

以上2个楼都是正解

要回复问题请先登录注册