我正在处理一个编程问题
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数字的组合。
当输入 n = 5,k = 4 时,输出应为[[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5]],以下是我的 Golang 解决方案:
func combine(n int, k int) [][]int {
result := [][]int{}
comb := []int{}
subcom(0, k, n, &comb, &result)
return result
}
func subcom(s, k, n int, comb *[]int, result *[][]int) {
if k > 0 {
for i := s + 1; i <= n-k+1; i++ {
c := append(*comb, i)
subcom(i, k-1, n, &c, result)
}
} else {
*result = append(*result, *comb)
}
}
我认为我的解决方案是正确的,但它返回了[[1 2 3 5] [1 2 3 5] [1 2 4 5] [1 3 4 5] [2 3 4 5]]。
调试后,我发现在一开始将[1 2 3 4]添加到结果中,但后来更改为[1 2 3 5],导致出现两个[1 2 3 5]的重复。但我无法找出问题所在。
c:=append(*comb, i)
首先将 i 添加到 comb 中,然后决定是否需要为 c 创建一个新的切片吗? - Tsonglew0xc000018260ath, 0xc000018260ath, 0xc000018280ath, 0xc0000182a0ath, 0xc0000182c0ath
第一个和第二个共享了相同的地址,但其他的没有,我想不出原因。 - Tsonglew