【问题标题】:recursivly determine if there is a subset sum of a positive int array that matches a given int argument?递归确定是否存在与给定 int 参数匹配的正 int 数组的子集和?
【发布时间】:2017-06-14 07:17:13
【问题描述】:

解决方案应该是递归的,零是任何集合的元素,关键是你可以多次使用集合的元素。

例如,如果数组是 {3,5,7},那么 17 将返回 true,因为 5+5+7=17 但是 4 会返回 false。

我试过这个:

public static boolean isSumOf(int [] s, int n)
{
        return isSumOf(s, s.length, n);
}
static boolean isSumOf(int s[], int length, int n)
{
   // Base Cases
   if (n == 0)
   {
       return true;
   }

   if (length == 0 && n != 0)
   {
       return false;
   }

   // If last element is greater than sum, then ignore it
   if (s[length-1] > n)
   {
       return isSumOf(s, length-1, n);
   }


   /* else, check if sum can be obtained by any of the following
      (a) including the last element
      (b) excluding the last element   */
   return isSumOf(s, length-1, n) || isSumOf(s, length-1, n-s[length-1]);
}

但它排除了多次添加元素的能力

【问题讨论】:

    标签: java arrays algorithm recursion backtracking


    【解决方案1】:

    不要缩短数组,只需像这样遍历循环中的所有值:

    //base cases
    ...
    res = false;
    for(i=0; i<length; i++)
        if (s[i]<= n)
            res = res ||  isSumOf(s[], length, n - s[i]);
    return res;
    

    如果不允许循环,则在有和没有最后一个元素的情况下调用递归(注意我在第二次调用中删除了-1):

    return isSumOf(s, length-1, n) || isSumOf(s, length, n-s[length-1]);     
    

    【讨论】:

    • 我忘了说我不允许使用循环,但它是一个有趣的方向......
    • 哇,我简直不敢相信!我试图解决这个问题好几个小时......非常感谢!
    【解决方案2】:

    试试这个。

    static boolean isSumOf(int s[], int length, int n) {
       if (n == 0)
           return true;
       if (length == 0)
           return false;
       int last = s[length - 1];
       if (last > n)
           return isSumOf(s, length - 1, n);
       return isSumOf(s, length - 1, n)
           || isSumOf(s, length - 1, n - last)
           || isSumOf(s, length, n - last);
    }
    

    结果

    int[] array = {3, 5, 7};
    int length = array.length;
    System.out.println(isSumOf(array, length, 12));  // true
    System.out.println(isSumOf(array, length, 5));   // true
    System.out.println(isSumOf(array, length, 8));   // true
    System.out.println(isSumOf(array, length, 25));  // true
    System.out.println(isSumOf(array, length, 4));   // false
    

    【讨论】:

    • @SanketMakani 抱歉,我改变了答案。
    【解决方案3】:

    您的实现更多的是标准子集求和,其中在求和操作期间不允许重复元素。

    但您的要求允许重复元素。

    例如,如果数组是 {3,5,7},那么 17 将返回 true,因为 5+5+7=17 但 4 将返回 false。

    这就是您没有得到结果的原因。正如 MBo 在总和计算期间检查所有元素所指出的那样有帮助。

    注意:如果要求找到所有这样的组合,那么它更像是coin exchange problem

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2013-12-02
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多