【发布时间】:2018-04-11 06:36:03
【问题描述】:
这是一种递归回溯方法,用于确定给定数组的总和是否可以达到目标数量。 这有效:
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;
}
这不是:
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?- 与第一种方法一样吗?当堆栈耗尽时它最终返回 - 如果没有,你会有一个堆栈溢出。 -
返回目标==0不应该结束栈吗?
-
!false等于true,所以在第二个程序中,您将重复 bothgroupSum调用
标签: recursion return-value recursive-backtracking