Subset sum overlapping dilemma recursively

倖福魔咒の 提交于 2019-12-13 09:48:04

问题


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.



来源:https://stackoverflow.com/questions/54076333/subset-sum-overlapping-dilemma-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!