[英]How does recursive of number sum work in java?
我有使用递归方法调查 groupSum 的代码。 我不明白这个例子中的递归是如何工作的。 我使用了调试,但仍然不明白。
public class test {
public boolean groupSum(int start, int[] nums, int target) {
if(target == 0)
return true;
if (start == nums.length)
return false;
if (groupSum( start+1, nums, target-nums[start])) // what is the meaning of this line ? can we change this line to make the code easier to understand ?
return true;
return groupSum( start+1, nums, target);
}
public static void main(String[] args) {
int x = 0;
int y [] = {2,4,8};
int k = 10;
test t = new test();
boolean result = t.groupSum(x,y,k);
System.out.println(result);
}
}
谢谢
有两个递归调用
groupSum( start+1, nums, target-nums[start])
如果我们减去nums[start]
处的值,尝试看看我们是否可以达到剩余的目标
或者我们可以在没有这个数字的情况下达到目标。
groupSum( start+1, nums, target);
如果调试器没有帮助您可以添加调试语句
public static void main(String[] args) {
int x = 0;
int[] y = {2, 4, 8};
int k = 10;
boolean result = groupSum(x, y, k);
System.out.println(result);
}
public static boolean groupSum(int start, int[] nums, int target) {
System.out.println("groupSum(" + start + ", " + Arrays.toString(nums) + ", " + target + ")");
if (target == 0)
return true;
if (start == nums.length)
return false;
if (groupSum(start + 1, nums, target - nums[start]))
return true;
System.out.print("or ");
return groupSum(start + 1, nums, target);
}
印刷
groupSum(0, [2, 4, 8], 10)
groupSum(1, [2, 4, 8], 8)
groupSum(2, [2, 4, 8], 4)
groupSum(3, [2, 4, 8], -4)
or groupSum(3, [2, 4, 8], 4)
or groupSum(2, [2, 4, 8], 8)
groupSum(3, [2, 4, 8], 0)
true
你可以看到它尝试了所有剩下-4
的值,然后它返回并尝试不包括8
,然后尝试不包括4
,结果证明是成功的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.