How do I return the combination sum in python using recursion?

Viewed 29

An array of distinct integers (candidates) and a target integer (target) , return a list of all unique combination of candidates. where the chosen numbers sum to target. candidates=[2, 3, 6, 7], target=7 output=[[2, 2, 3], [7]]

Here I'm struggling to get the answer by doing this problem by 0/1 Knapsack using recursion with driver code.


def combination_sum(array, target, N):
    if N==0 and target==0:
        return 0
    if (array[N-1] <= target):
        return combination_sum(array[N-1], N-1, target-array[N-1]) or combination_sum(array, target, N-1)
    
    else:
        return combination_sum(array, N-1, target)

if __name__=="__main__":
    array=[2, 3, 6, 7]
    target=7
    N=len(array)
    combination_sum([2, 3, 6, 7], 7, N)
language-python```


This the error Im getting
```Python
PS C:\Users\LENOVO\Downloads> & C:/Users/LENOVO/AppData/Local/Microsoft/WindowsApps/python3.10.exe c:/Users/LENOVO/Downloads/reversion1.py
Traceback (most recent call last):
  File "c:\Users\LENOVO\Downloads\reversion1.py", line 15, in <module>
    combination_sum([2, 3, 6, 7], 7, N)
  File "c:\Users\LENOVO\Downloads\reversion1.py", line 6, in combination_sum
    return combination_sum(array[N-1], N-1, target-array[N-1]) or combination_sum(array, target, N-1)
  File "c:\Users\LENOVO\Downloads\reversion1.py", line 5, in combination_sum
    if (array[N-1] <= target):
TypeError: 'int' object is not subscriptable```
0 Answers
Related