【发布时间】:2016-03-20 19:41:28
【问题描述】:
如何仅使用整数数组将整数添加到某个数字?这就是我到目前为止所拥有的。我必须递归地做。
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"); }
这是输出:
应该总是打印出来的。
- 是的
- 假
- 是的
- 是的
- 是的
- 是的
- 是的
- 是的
- 是的
- 是的
【问题讨论】:
-
我自己不明白这个问题。应该发生什么?
-
使用数组中的数字添加到目标整数。