【问题标题】:Determining if there exists a subset in a Array of Integers that sums to a given target value under a couple of conditions确定在几个条件下总和为给定目标值的整数数组中是否存在子集
【发布时间】:2014-07-19 05:41:47
【问题描述】:

问题:

给定一个整数数组,是否可以选择一组整数 整数,使得组与给定目标相加 附加约束:如果数组中的一个值被选择在 组,数组中紧随其后的值不能是 选择。

例如:-

groupNoAdj(0, {2, 5, 10, 4}, 12) → 真

groupNoAdj(0, {2, 5, 10, 4}, 14) → 假

groupNoAdj(0, {2, 5, 10, 4}, 7) → 假

正如您在最后一种情况中看到的那样,尽管存在子集 {2,5},其总和为目标值“7”,但它们是相邻值,因此不能一起选择。 还有一个条件是不能使用局部变量。

我想出了以下解决方案:

public boolean groupNoAdj(int start, int[] nums, int target) {
    if(start==nums.length)
        return target==0;
    if(start==nums.length-1&&!(target==0))
        return (target-nums[start]==0);


    if(target==0)
       return true;

    if((start<nums.length-1)&&groupNoAdj(start+1, nums, target-nums[start]))
           return groupNoAdj(start+2, nums, target-nums[start]);

   return groupNoAdj(start+1, nums, target);
}

但在 groupNoAdj(0, {2, 5, 10, 4, 2}, 7) 的情况下它会失败 它实际上应该返回 true 时返回 false

在这种情况下无法真正找出导致它失败的原因。

【问题讨论】:

  • 你尝试调试你的代码了吗?
  • 为什么要调用两个约束一个条件?总和验证没有局部变量和非连续测试。
  • 好吧实际上有 2 个,所以更新了问题的摘要。
  • 这只是解决问题的一个条件,不要用于保持设计的视野。
  • @Anirudh 或者更像是一个专注于递归的“提示”:)

标签: java arrays


【解决方案1】:

你在最后的情况下遗漏了一些东西:

public static void main(String[] args) {
    int[] arr1 ={2, 5, 10, 4};
    int[] arr2 = {2, 5, 10, 4};
    System.out.println(groupNoAdj(0, arr1, 12)); // prints true
    System.out.println(groupNoAdj(0, arr2, 7));  // prints false
}

public static boolean groupNoAdj(int start, int[] nums, int target) {

    if(target == 0)
        return true;

    if(start == nums.length)
        return target==0;

    if(start == nums.length-1)
        return target-nums[start] == 0;

    return
            groupNoAdj(start+2, nums, target-nums[start]) || // either pick the "current" item (and skip the "next") 
            groupNoAdj(start+1, nums, target);               // or don't pick it
}

【讨论】:

  • 感谢@alfasin 的解决方案,虽然它解决了问题中的情况,但现在它失败了 -->groupNoAdj(0, {9}, 0) 应该返回 true,但它返回 false
  • @Anirudh 如果你想允许“空子集”添加一个条件,如果 target == 0 总是返回 true
  • @Anirudh 不是真的,我写了“总是”,这意味着这个条件应该成为第一个条件。您描述的情况属于start == nums.length-1,并且由于在target == 0 之前检查了此条件,因此它返回false。更新后的答案应该有效。
猜你喜欢
  • 2020-06-30
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2017-02-20
  • 2013-11-03
相关资源
最近更新 更多