Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

Backtracking solution in ruby

def exact_sum?(sum, arr)
return true if sum==0
return false if sum < 0 || arr.empty?
# now we are checking both cases
exact_sum?(sum - arr[0], arr[1,arr.length]) || exact_sum?(sum, arr[1,arr.length])
end

puts exact_sum?(12, [1, 2, 3, 4, 5]);
# => true
Source by hackernoon.com #
 
PREVIOUS NEXT
Tagged: #Backtracking #solution #ruby
ADD COMMENT
Topic
Name
9+9 =