Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using recursion to solve the subset sum problem

I want to calculate the number of subsets of the array A = [2, 1, 1, 4] that sum to 2. There are 2 ways: (A[0]) and (A[1], A[2]). My code for computing this is:

 def W(number, index):
     A = [2, 1, 1, 4]
     if number < 0 or index < 0:
          return 0
     elif number==0:
          return 1
     else: 
          return W(number, index-1) + W(number - A[index], index)

Right now, when I call the function with W(2,3), I get 4 instead of 2. My problem is that my code also calculates the possibility (A[1], A[1]) and (A[2], A[2]). Is there any way to fix it while still using recursion?

like image 461
AlphaList Avatar asked Aug 08 '26 15:08

AlphaList


1 Answers

The call to W(number - A[index], index) should be W(number - A[index], index - 1); otherwise, you allow for the possibility of double-counting an element in your subset sum.

Here is a code snippet that fixes this issue. For each element, we decide whether or not to add it to our sum. If the element allows our target to reach 0, we add 1 to our total count of possibilities, then recurse to see if there are any other ways to reach the target without adding the element we're currently examining:

A = [2, 1, 1, 4]

def W(number, index):
     if number < 0 or index < 0 :
          return 0
     elif number - A[index] == 0:
         return 1 + W(number, index - 1)
     else: 
          return W(number, index - 1) + W(number - A[index], index - 1)
          
print(W(1, 3)) # Prints 2
like image 170
BrokenBenchmark Avatar answered Aug 11 '26 04:08

BrokenBenchmark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!