Download The Subset sum problem
Transcript
int oldnumsj = nums[j]; //save value of nums[j] before recursive call
nums[i] = result;
nums[j] = nums[n-1];
combine(n-1);
nums[i] = oldnumsi; //restore value of nums[i]
nums[j] = oldnumsj; //restore value of nums[j]
…
}
However, for Countdown13, it was easier to place the result at the end of the array, and negate the values
of nums[i] and nums[j]. I would then ignore any negative values in the recursive call. We therefore
needed the nums array to be of length 2n-1 to allow space for the result of each operation. Since one
element has been added to the array, the recursive call will be combine(n+1, j+1). We pass j+1 as we
only want to look at the next value of j with each value of i, as explained in Section 4.3.
combine(n, jNext){
…
nums[i] = - nums[i]; //negate to stop reuse
nums[j] = - nums[j]; //negate to stop reuse
nums[n] = result; // place result at the end of array
combine(n+1, j+1);
nums[i] = - nums[i]; // un-negate for next iteration
nums[j] = - nums[j]; // un-negate for next iteration
…
}
Legal Operations
In the Countdown numbers game you are only allowed to use integers, even as intermediary results. I
therefore decided that if in the evaluate method a non-integer result was obtained (as might happen with
division), I would return a –1 flag, which I would catch in the countdown method and ignore that value.
case '/': //division
if (num1 >= num2)
if (num1 % num2 == 0)
return num1/num2;
21