Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Last active April 6, 2016 22:55
Show Gist options
  • Save aniruddha84/ea35de3439c83cf3d0933e8f0f784291 to your computer and use it in GitHub Desktop.
Save aniruddha84/ea35de3439c83cf3d0933e8f0f784291 to your computer and use it in GitHub Desktop.
Given an input array and target sum, find all possible ways the elements of the array can be added upto get target
# Given an input array and target sum, find all possible ways the elements of the array can be added upto get target
# sub_set_sum([10, 7, 5, 18, 12, 20, 15], 35) => [
# [10, 7, 18],
# [10, 5, 20]
# [5, 18, 12],
# [20, 15]
# ]
require 'set'
def subset_sum(arr, sum, curr_arr = [], result = Set.new)
return if arr.nil?
if sum == 0
unless result.include? curr_arr
puts curr_arr.to_s
result.add(curr_arr)
end
end
return if arr.empty?
num = arr[0]
# not including the first element
subset_sum(arr[1..-1], sum, Array.new(curr_arr), result)
# including the first element
subset_sum(arr[1..-1], sum - num, Array.new(curr_arr << num), result)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment