递归添加子集

时间:2014-03-03 00:51:56

标签: java recursion combinations

我有这种情况适用于输入:

{-5,0,5}, 2, 0   // which correctly evaluates to true
{-5,0,5}, 3, 4   // which correctly evaluates to false
{-5,0,5}, 3, 0   // which correctly evaluates to true

但输入:

{6,5,6}, 2, 12  // says false when true

它没有得到正确的布尔值... 有人可以帮助调试问题吗?

public static boolean subset(int[] array, int n, int target) {
    for (int i = 0; i < array.length; i++) {
        int[] list = new int[array.length - 1];

        for (int j = 0; j < array.length - 1; j++) {
            list[j] = array[j+1];
        }
        subset(list, n, target);
    }

    int sum = 0;
    for (int i = 0; i < array.length; i++) {
        sum += array[i];
    }

    if (sum == target) {
        return true;
    }
    else {
        return false;
    }
}

2 个答案:

答案 0 :(得分:0)

不确定你要计算什么,但我怀疑你的问题在于子集(list,n,target)的递归调用。您没有更改对象而忽略了返回值。 另外:你根本没有使用变量“n”。

答案 1 :(得分:0)

您对递归的返回值没有任何作用。

这一行:

subset(list, n, target);

应改为:

if (subset(list, n, target)){
    return true;
}

此外,您不对n变量

执行任何操作

我喜欢你努力的人,所以我让你更容易:)。

public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5};
    int n = 3;
    int sum = 10;
    System.out.println(subset(array, n, sum));
}

public static boolean subset(int[] array, int n, int sum) {
    //If I have enough numbers in my subarray, I can check, if it is equal to my sum
    if (array.length == n) {
        //If it is equal, I found subarray I was looking for
        if (addArrayInt(array) == sum) {
            return true;
        } else {
            return false;
        }
    }

    //Trying all possibilites and doing recursion
    for (int i = 0; i < array.length; i++) {
        //if some recursion returned true, I found it, so I can also return true
        int[] subarray = new int[array.length - 1];
        int k = 0;
        for (int j = 0; j < subarray.length; j++) {
            if (i == j) {
                k++;
            }
            subarray[j] = array[j + k];
        }
        if (subset(subarray, n, sum)) {
            return true;
        }
    }

    //If I didnt find anything, I have to return false
    return false;
}

public static int addArrayInt(int[] array) {
    int res = 0;
    for (int i = 0; i < array.length; i++) {
        res += array[i];
    }
    return res;
}

但是,你不了解递归的基础知识,你很接近,但我认为你错过了主要想法:)。我建议你递归地尝试计算因子,然后是Fibonacci,它可以提供帮助,并且有互联网上的教程。