子集和算法的复杂度,带有一些额外条件

问题描述 投票:0回答:1

问题是关于finding if there exists a subset in an array of ints that sums to a target with following tweaks

  • 必须包含5的所有倍数。
  • 如果有1后跟5的倍数,那么就不能包含它。

有一个

标准溶液

  /*
   * Given an array of ints, is it possible to choose a group of some of the ints,
   * such that the group sums to the given target with these additional constraints:
   * all multiples of 5 in the array must be included in the group.
   * If the value immediately following a multiple of 5 is 1,
   * it must not be chosen. (No loops needed.)
   *
   * groupSum5(0, {2, 5, 10, 4}, 19) → true
   * groupSum5(0, {2, 5, 10, 4}, 17) → true
   * groupSum5(0, {2, 5, 10, 4}, 12) → false
   * groupSum5(0, {3, 5, 1}, 9) → false
   * groupSum5(0, {2, 5, 4, 10}, 12) → false
   * groupSum5(0, {3, 5, 1}, 5) → true
   * groupSum5(0, {1, 3, 5}, 5) → true
   * groupSum5(0, {1}, 1) → true
   */
  public boolean groupSum5(int start, int[] nums, int target) {
    if (start >= nums.length) return (target == 0);
    if (nums[start] % 5 == 0) {
       if (start < nums.length - 1 && nums[start + 1] == 1){
         return groupSum5(start + 2, nums, target - nums[start]);
       }
      return groupSum5(start + 1, nums, target- nums[start]);
    }
    return groupSum5(start + 1, nums, target - nums[start])
              || groupSum5(start + 1, nums, target);
  }

我的方法

public boolean groupSum5(int start, int[] nums, int target) {
        final int len = nums.length;

        if (start == len) {
            return target == 0;
        }

        if (start > 0 && nums[start] == 1 && (nums[start- 1] % 5) == 0 ) {
            return groupSum5(start + 1, nums, target);
        }

        if (groupSum5(start + 1, nums, target - nums[start])) {
            return true;
        } if ((nums[start] % 5) != 0
                & groupSum5(start + 1, nums, target)) {
            return true;
        }
        return false;
    }

在时间复杂度方面,上述两种方法哪个更好?

如果我没记错的话,标准解决方案的复杂度或第一个解决方案的复杂度大于指数((3 ^ n)]?我想如果我们考虑一下递归调用,那么说复杂度为((4 ^ n)

是正确的吗?
java algorithm big-o subset-sum
1个回答
1
投票

我认为您的代码是错误的。 groupSum5(0,[0,1,1],1)在您的代码中返回false,因为两个1都被排除在外。在最坏的情况下,正确的groupSum5和您的groupSum5均为O(2 ^ n)。尽管groupSum5在第一段代码中以文本形式出现了4次,但其中只有两个调用可以在单个堆栈帧中发生

© www.soinside.com 2019 - 2024. All rights reserved.