简体   繁体   中英

Subset sum overlapping dilemma recursively

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM