Recursion on the whole has been difficult to understand, but I have been getting through a few easier problems and gaining understanding.
As far as this problem goes, I'll try to write the code I need to solve this one.
Based on the input of 0 {5, 10, 2, 2, 3, 3} 15 - which would yield true. (The first element being an index int).
// 'a' being the array, 'i' the index, 'sum' an int to store the total, 'n' being the expected result).
static void checkSum(int[] a, int i, int sum, int n)
{
int total = sum; //this will set total to the value passed to the method (starts at 0)
if ( i < a.length ) // if i is less than a.length (5)
{
total += a[i]; // total is equal to total plus the value stored in element i
i += 2; // increment i by 2 to get the next value
checkSum(a, i, total, n); // recur on this method passing the updated i int
}
else
if ( total == n ) // if the problem is solved
System.out.print(true);
else
System.out.print(false);
}
That works as long as the sum expects the method to only be run from the first element onwards, incrementing the index by 2 each time.
In {2, 5, 10, 4, 2} - 7, this wouldn't work considering the 5 and 2 would never be added together.
This is where I'm stuck!