'Incomplete solution to the subset sum problem
I am to write a function with the signature
bool groupSum(int arr[], bool lut[], int n, int target, int index);
for the partial sum problem, which besides the statement that a subset of the passed field reaches or does not reach the target sum also outputs a possible feedback. If the sum can be specified, then the individual summands are to be returned. Otherwise the output shall be that for the targeted value of the sum the problem is not solvable.
An example output could be:
Test:
int array[] = {-4, -2, 1, 3, 5, 9, 12}; int val = 18;
Output:
18 is sum of -4 -2 3 9 12
Test:
int array[] = {17, -2, 13, 18, 9, 8, 0}; int val = 1;
Output:
Not solvable for 1
What I wrote so far ist the following:
bool groupSum(int arr[], bool lut[], int n, int target, int index) {
/*
arr is the field containing the numbers whose undersets are considered.
Here lut is a field of the type bool, which was initialized completely
with false. This should be set to true as soon as a number is evaluated
useful at the corresponding index position, so that the appropriate number can
be output at the end. Furthermore, n represents the length of the field,
target the value of the sum of the subset of the field arr and index the
starting point for the recursion.
*/
if (index == n - 1 && target == 0) {
return true;
}
else {
if (groupSum(arr, lut, n, target, index)) {
lut[index] = true;
return groupSum(arr, lut, n, target - arr[index], index+1);
}
else {
return groupSum(arr, lut, n, target, index + 1);
}
}
return false;
}
Now, however, I am faced with the problem with my already formulated code that on the one hand I do not know exactly how I can formulate the recursion case so that in particular also the field lut is correctly occupied with values true or false. Furthermore, it is not yet clear to me how I can realize the indicated output via printf.
I would appreciate your tips.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
