The problem is Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? Target below is 10.
I know to solve the problem in a different way. Trying to understand the below code. This should give me deeper understanding on recursion.
Could any of you explain, when Line #13(groupSum(start + 1, nums, target - nums[start])) would be executed and when Line #14(groupSum(start + 1, nums, target)) would be executed or both execute parallel y. By looking into the print-line display I see the Line #14 gets executed only one Line#13 is false. Is this the way it works.
I can understand Line #13 and 14 are same statement. For explaining clarity, I have used the Line #s to differentiate recursively called function. Sorry about that!
Your question is nothing specifically to do with recursion, and is mainly related to java syntax of the OR operator.
In Java, the boolean operators are "lazy" by default.
So when evaluating A || B (A or B), It will first evaluate A (the left hand side). If A is true, it does not bother to evaluate B, as in boolean logic true ORed with anything is always going to be true.
The person coding this example has just taken advantage of this feature, and the fact that this recursive method returns a boolean value.
Essentially it is the same as
It just takes less lines of code.
The down side is that it makes it more difficult to read and understand.
Did you ever grow anything in the garden of your mind? - Fred Rogers. Tiny ad: