我有这段代码用于使用递归方法调查 groupSum 。 我不明白这个例子中的递归是如何工作的。我用了debug,但还是不明白。
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
结果是成功的。
关于java - java中数字和的递归如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36811474/