Subset sum overlapping dilemma recursively

2019-09-26 07:52发布

问题:

I'm studying recursive logic that one of the problems is subset sum. AFAI read, there are overlaps when it is run by recursion. But, I cannot figure out how there are. Also, I read that to overcome the issue DP can be used but I want to comprehend how the recursion overcome the problem. Could you picturize an example with overlapping?

Pseudo-code,

def hasSum( array, start, sum):
   if sum == 0:
       return true

   if start > array.length - 1:
       return false;

   return hasSum(array, start + 1, sum - array[start])
           or hasSum(array, start + 1, sum)

I cannot associate the logic with the following picture, I'm certainly overlook a point / points.

回答1:

There is overlap caused by this line here:

return hasSum(array, start + 1, sum - array[start])
           or hasSum(array, start + 1, sum)

If the algorithm doesn't find a valid condition with the first hasSum (which because of recursion has already gone through the entire array by the time is returns to this point), it will try again with the second hasSum which ignores the value of this current index. This means that the algorithm checks the same indexes multiple times.