0

This is a recursive backtracking method that finds whether or not a given array can sum to a target amount. This works:

  public boolean groupSum(int start, int[] nums, int target) {
  if(start >= nums.length)
    return target ==0;
  if(!groupSum(start+1,nums,target-nums[start]))
    return groupSum(start+1,nums,target);
  return true;
}

This doesn't:

  public boolean groupSum(int start, int[] nums, int target) {
  if(start >= nums.length)
    return target ==0;
  if(!groupSum(start+1,nums,target-nums[start]))
    return groupSum(start+1,nums,target);
  return false;
}

How does the method even reach the final return statement?

  • Can you highlight the difference in the two programs? I've been looking for over a minute and I still don't see it... – Mulan Apr 10 '18 at 16:18
  • It's the final return statement in both methods. – Jorge Gomez Apr 10 '18 at 16:20
  • `How does the method even reach the final return statement?` - same way the first method does? It returns finally when the the stack is depleted - if it didn't you'd have a stackoverflow. – Mark Apr 10 '18 at 16:21
  • shouldn't the return target ==0 end the stack? – Jorge Gomez Apr 10 '18 at 16:22
  • `!false` is equal to `true`, so in the second program, you will recur *both* `groupSum` calls – Mulan Apr 10 '18 at 16:24

1 Answers1

0

In your program you have two if statements that both ends up returning. If both of them are false, then the last return is in effect. Thus you can expect this to be true when you hit the last line of your function:

start < nums.length && groupSum(start + 1, nums, target - nums[start])

I think perhaps a little more clear version would be this:

public boolean groupSum(int start, int[] nums, int target) {
  if (start >= nums.length)
    return target == 0;
  if (groupSum(start + 1, nums, target - nums[start]))
    return true;
  return groupSum(start + 1, nums, target);
}

It is exactly the same logic except I've switched the two last and reversed the predicate (removed the not).

Sylwester
  • 47,942
  • 4
  • 47
  • 79