2017-01-07 2 views
0

int 배열을 사용하면 시작 색인에서 시작하여 그룹이 주어진 대상에 합산되도록 int 중 일부 그룹을 선택할 수 있습니까? 그러나 모든 6이 선택되어야한다는 추가 제약 조건이 있습니다.동적 프로그래밍 : 서브셋 논리

groupSum6 (0, [5, 6, 2, 8)에 해당

groupSum6 → ​​(0, [5, 6, 2, 9) 거짓

groupSum6 (0 → [5 , 6, 2], 7) → 거짓

어디서 잘못되었는지 명확히하고 싶었습니다. nums [시작] == 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; 
} 

답변

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

BTW. 더 적은 수의 코드 줄에서 처리 할 수 ​​있습니다.

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

} 
+0

답장을 보내 주셔서 감사합니다. 오류 사과, 나는 num [시작] 대신 "시작"을 말합니다. –

+0

질문 : start ++와 start + 1을 사용하는 것에 차이가 있습니까? –

+0

사과를해서는 안되며 우리는 인간이며 오류를 범하고 있습니다. 정상입니다. – czojo26