Created
September 18, 2018 06:00
-
-
Save woodRock/e239594eb0e38530d84346218665641e to your computer and use it in GitHub Desktop.
Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null. Integers can appear more than once in the list. You may assume all numbers in the list are positive. For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
def isSubsetSum(set,n, sum) | |
return true if (sum == 0) | |
return false if (n == 0 and sum != 0) | |
return isSubsetSum(set, n - 1, sum) if (set[n - 1] > sum) | |
return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum - set[n-1]) | |
end | |
s = [12, 1, 61, 5, 9, 2] | |
k = 24 | |
puts isSubsetSum(s, s.size(), k) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment