Java 如何使用整数数组添加到目标数?
如何仅使用整数数组将整数添加到某个数字?这就是我目前所拥有的。我必须递归地做Java 如何使用整数数组添加到目标数?,java,arrays,recursion,Java,Arrays,Recursion,如何仅使用整数数组将整数添加到某个数字?这就是我目前所拥有的。我必须递归地做 public static boolean sumsToTarget(int[] arr, int target){ return sumsToTarget(arr, target, 0, 0, 0); } private static boolean sumsToTarget(int[] arr, int target, int startIndex, int endIndex, int total){
public static boolean sumsToTarget(int[] arr, int target){
return sumsToTarget(arr, target, 0, 0, 0);
}
private static boolean sumsToTarget(int[] arr, int target, int startIndex, int endIndex, int total){
if(endIndex >= arr.length){
if(startIndex >= arr.length){
return false;
}
return sumsToTarget(arr, target, startIndex + 1, startIndex + 1, 0);
}
total += arr[endIndex];
if(total == target){
return true;
}else if(total >= target){
return sumsToTarget(arr, target, startIndex, endIndex + 1, total - arr[endIndex]);
}else{
return sumsToTarget(arr, target, startIndex+1, startIndex+1, total) || sumsToTarget(arr, target, startIndex, endIndex + 1, total) || sumsToTarget(arr, target, startIndex, endIndex + 2, total);
}
}
这就是我测试代码的方式
int[] a = {1, 3, 5, 7, 9};
System.out.println("Should always print out true.");
try{ System.out.println("1. " + (ProjectTwo.sumsToTarget(a, 10)==true)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("2. " + (ProjectTwo.sumsToTarget(a, 40)==false)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("3. " + (ProjectTwo.sumsToTarget(a, 17)==true)); } catch(Exception e){ System.out.println("failed"); }
int[] b = {-5, 100, 150, 12, 10, 200, 300, -4, 250, 600};
try{ System.out.println("4. " + (ProjectTwo.sumsToTarget(b, -5)==true)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("5. " + (ProjectTwo.sumsToTarget(b, 1)==true)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("6. " + (ProjectTwo.sumsToTarget(b, 601)==true)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("7. " + (ProjectTwo.sumsToTarget(b, 0)==false)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("8. " + (ProjectTwo.sumsToTarget(b, 12)==true)); } catch(Exception e){ System.out.println("failed"); }
int[] c = {5};
try{ System.out.println("9. " + (ProjectTwo.sumsToTarget(c, -5)==false)); } catch(Exception e){ System.out.println("failed"); }
try{ System.out.println("10. " + (ProjectTwo.sumsToTarget(c, 5)==true)); } catch(Exception e){ System.out.println("failed"); }
这是输出:
应该总是打印出真实的
考虑一下算法。您有一个值列表,希望尝试将它们相加的每个组合,以查看该组合是否与您的目标匹配 假设数字是
1
、3
和7
。所有组合将是:
= 0
1 = 1
3 = 3
1+3 = 4
7 = 7
1+7 = 8
3+7 = 10
1+3+7 = 11
要使用递归,您基本上需要取第一个数字(1
),并通过对其余数字进行递归调用来尝试使用和不使用该数字,到目前为止,总数为0
或1
在第二次调用中,您可以尝试使用和不使用3
。由于到目前为止调用它的总次数为0
或1
,因此最终将总共调用4次三级调用,到目前为止总共调用0
,3
,1
,4
等等
如果总数等于目标值,则停止递归并返回true
,这将停止递归,直至返回调用堆栈为止
可选:如果总数超过目标,您可以停止此组合的递归,因为任何进一步的递归都会离目标更远
现在尝试实现这个逻辑。我自己也不理解这个问题。应该发生什么?使用数组中的数字添加到目标整数。