如何使用整数数组添加目标数?

时间:2016-03-20 19:41:28

标签: 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){
    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 个答案:

答案 0 :(得分:1)

考虑算法。您有一个值列表,并且您想尝试将它们相加的每个组合,以查看组合是否与您的目标匹配。

我们说这个数字是137。所有组合都是:

      = 0
1     = 1
3     = 3
1+3   = 4
7     = 7
1+7   = 8
3+7   = 10
1+3+7 = 11

要使用递归,你基本上取第一个数字(1),并尝试使用和不使用该数字,通过对其余数字进行递归调用,以及总数到目前为止01

在第二次调用时,您可以尝试使用和不使用3。由于它的调用总数为01,因此最终总共会有4个3级调用,其总数为{{} 1}},031

等等。

如果总数等于目标,则停止递归并返回4,这应该一直停止递归调用堆栈。

可选:如果总数超过目标,则可以停止此组合的递归,因为任何进一步的递归都会远离目标。

现在尝试实现这个逻辑。