【问题标题】:Recursively adding subet递归添加子网
【发布时间】:2014-03-03 00:51:56
【问题描述】:

我有一个适用于输入的案例:

{-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;
    }
}

【问题讨论】:

  • 如果您告诉我们该方法应该完成什么,将会有所帮助。

标签: java recursion combinations


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你对递归的返回值什么都不做。

    这一行:

    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;
    }
    

    但是,您不了解递归的基础知识,您很接近,但我认为您缺少主要思想:)。我建议您尝试递归计算阶乘,然后尝试计算斐波那契,它会有所帮助,并且互联网上都有教程。

    【讨论】:

    • 有没有办法做到这一点,同时保留方法上的原始签名?
    • @user3362954 - 相同的参数,对吧?嗯,有可能,看看编辑过的代码
    • 感谢您对我的帮助!
    猜你喜欢
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 2011-11-03
    • 2021-03-21
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多