I have a recursive Backtracking problem for school, and I do not understand how I would go about solving it.
Given an array of integers, determine if it is possible to choose a group of those integers that add to a particular sum. Use a recursive method called sum_to_total
to solve the problem (no loops!).
Examples:
- "Array
[3, 6, 7]
" and "Sum 10" returns true, since3 + 7 = 10
- "Array
[1, 2, 3]
" and "Sum 6" returns true, since1 + 2 + 3 = 6
- "Array
[2, 4, 6]
" and "sum 5" returns false, since no combination of these numbers sum to 5
This is what I have got so far:
def self.sum_to_total(sum, array, index)
@@sum_num += array[index]
return false if @@sum_num > sum || @@sum_num < sum
return false if index<board.length || index<0
return true if @@sum_num == sum
return solvable(sum, array, index+1)
end
@@sum_num = 0
puts sum_to_total(10, [3, 5, 7], 0)
A few pointers would help.