动态编程:子集逻辑

时间:2017-01-07 23:00:39

标签: java

给定一系列整数,是否可以从起始索引开始选择一组整数,以便该组与给定目标相加?但是,附加约束必须选择所有6个。

groupSum6(0,[5,6,2,8)→true

groupSum6(0,[5,6,2,9)→false

groupSum6(0,[5,6,2,7)→false

只是想明确我哪里出错了。是否为nums声明了一个特例[start] == 6错误的做法?

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

 if (nums[start] >= nums.length) {return (target == 0);} 

 if (nums[start] == 6){ 
 return groupSum6(start++, nums, target - nums[start]);
 }

 if (groupSum6(start++, nums, target - nums[start])) {return true;}
 //if a particular number is choosen 

 if (groupSum6(start++, nums, target)) {return true;}
 //if that particular  number is not chosen

 return false;
}

1 个答案:

答案 0 :(得分:0)

问题:checkValue方法中整数a的值是多少?

int a = 4;
checkValue(a++);
void method(int value){
    System.out.println(a);
}

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

    if (start == nums.length) {return (target == 0);} //why did you compare some arbitrary number from array with length of this array? 

    if (nums[start] == 6){
        return groupSum6(start+1, nums, target - nums[start]);
    }

    if (groupSum6(start+1, nums, target - nums[start])) {return true;} //when you use start++ , you are calling the method with the same argument (i.e. start) recursively
    //if a particular number is choosen 

    if (groupSum6(start+1, nums, target)) {return true;}
    //if that particular  number is not chosen

    return false;
}

顺便说一句。你可以用更少的代码行来做到这一点:

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

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

    else if (nums[start] == 6){
        return groupSum6(start+1, nums, target - nums[start]);
    }

    else return (groupSum6(start+1, nums, target - nums[start])) || (groupSum6(start+1, nums, target)) ;

}