LeetCode77:组合。我在使用 Golang 编写递归算法时遇到堆栈溢出问题

问题描述 投票:0回答:1

LeetCode77:组合。我在使用 Golang 编写递归算法时遇到了堆栈溢出问题,即使只是测试 (3,2) 这么小的规模。

这是我的代码

package main

import (
    "fmt"
)

func combine1(n int, k int) [][]int {
    res := [][]int{}
    if k == 1 {
        for i := 1; i <= n; i++ {
            res = append(res, []int{i})
        }
        return res
    }
    //The k number contains the combination of digits n
    for _, combination := range combine1(n-1, k-1) {
        combination = append(combination, n)
        res = append(res, combination)
    }
    //The k number does not contain the combination of the number n
    for _, combination := range combine1(n-1, k) {
        res = append(res, combination)
    }
    return res
}

func main() {
    fmt.Println("运行")
    
    fmt.Println(combine1(3,2))
}


我已经检查了我的代码和逻辑很多次了。看起来一切都很好?

go recursion stack-overflow
1个回答
0
投票

抱歉,经过调试,我发现我的算法没有达到第二个递归部分的极限。

//The k number does not contain the combination of the number n
if n>k{
    res = append(res, combine(n-1, k)...)//...表示将数组中的元素打散
}
© www.soinside.com 2019 - 2024. All rights reserved.