我的问题是,作为if / else语句的条件,方法调用到底如何工作?
我知道递归是一种通过更改其参数值来调用自身的方法,可以尝试一种解决方案,如果正确,则停止递归。
这种简单的递归对我来说很有意义:
/* Given a string, compute recursively (no loops) a new string where all the
* lowercase 'x' chars have been changed to 'y' chars.
*/
public String changeXY(String str) {
if(str.length() == 0)
return str;
if(str.charAt(0) == 'x')
return 'y' + changeXY(str.substring(1));
return str.charAt(0) + changeXY(str.substring(1));
}
但是当将方法调用作为if语句的条件时,我不明白它是如何工作的? 正在检查什么?如何确定方法调用是否为true,然后可以返回true以停止递归?如果不是正确的可能性,如何“保存”然后回溯呢?通过返回比较,基本情况如何工作?
/* 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? This is a classic
* backtracking recursion problem. Rather than looking at the whole array,
* our convention is to consider the part of the array starting at index
* start and continuing to the end of the array. The caller can specify the
* whole array simply by passing start as 0. No loops are needed -- the
* recursive calls progress down the array.
*/
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;
if(groupSum(start+1, nums, target))
return true;
return false;
}
这两个代码均来自此github。
谢谢!