且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将递归函数重写为尾递归函数

更新时间:2023-11-26 23:41:22

一种解决堆栈溢出问题的方法是手动模拟调用堆栈.

One way for you to get around the stack overflow problem would be to simulate the callstack manually.

def numWays(n, arr):
    call_stack = [(n, arr)]
    answer = 0
    while call_stack:
        n, arr = call_stack.pop(0)
        for item in arr:
            if item <= n:
                if n == item:
                    answer += 1
                else:
                    call_stack.insert(0, (n-item, arr))
    return answer


li = [i for i in range(1, 7)]
print(numWays(5, li))

输出:

16