简体   繁体   English

子集和递归重叠的困境

[英]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. AFAI读取,递归运行时有重叠。 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.另外,我读到可以使用 DP 来克服这个问题,但我想了解递归如何克服这个问题。 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.如果算法没有找到第一个hasSum的有效条件(由于递归,在返回到这一点时已经遍历了整个数组),它将再次尝试使用第二个hasSum忽略 this 的值当前索引。 This means that the algorithm checks the same indexes multiple times.这意味着该算法多次检查相同的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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