找到解决方案后,Python 停止递归

Koe*_*oen 4 python recursion sum

我有一个递归函数,它试图在给定整数列表的情况下形成某个总和。该功能有效,但它为我提供了所有可能的解决方案。一旦找到解决方案,我想摆脱递归函数。我怎样才能做到这一点?以下是该函数的(伪)代码:

function find_sum(list_of_integers, target_sum, partial_solution):
    if partial_solutions == target_sum:
        return True
    if partial_solution > target_sum:
        return

    for i in range(len(list_of_integers)):
        n = list_of_integers[i]
        remaining = list_of_integers[i+1:]
        find_sum(remaining, target_sum, partial_solution + n)
Run Code Online (Sandbox Code Playgroud)

所以我只想知道target_sum是否可以由整数列表组成,我不需要所有的解决方案。

Mar*_*ers 5

您需要检查递归调用的返回值;如果True返回,立即传播,而不是继续循环:

for i in range(len(list_of_integers)):
    n = list_of_integers[i]
    remaining = list_of_integers[i+1:]
    found = find_sum(remaining, target_sum, partial_solution + n)
    if found:
        return True
Run Code Online (Sandbox Code Playgroud)