Ich schrieb das folgende rekursive Programm angehängt, das die Kombination von Zahlen findet, die hinzugefügt werden können, um den Sollwert zu machen:auf eine Liste in rekursive Funktion
arr = [1, 2, 2, 3, 5]
target = 8
def comb_sum(arr, current_index, target, result, ans):
if target == 0:
print result
ans.append(result)
return 0
if target < 0:
return 1
if current_index == len(arr):
return 1
result.append(arr[current_index])
comb_sum(arr, current_index+1, target - arr[current_index], result, ans)
result.pop()
comb_sum(arr, current_index+1, target, result, ans)
return ans
print comb_sum(arr, 0, target, [], [])
Da ich arr.append bin mit() anhängen die result
, erwartete ich die korrekte Ausgabe.
Obwohl das Programm korrekt ist, kann ich keine result
ans
Liste hinzufügen.
Was ist los?
Ich erwarte diese Ausgabe: [[1, 2, 2, 3], [1, 2, 5], [1, 2, 5], [3, 5]]
Aber stattdessen bekomme ich diese Ausgabe: [[], [], [], []]
Was ist Ihre erwartete Ausgabe? –
aktualisiert die Frage – yask
@yask verwenden Sie Python 2.7? – wind85