Created
June 16, 2017 21:49
-
-
Save evidanary/e8f702d6ca504c708ff0ddaa19412a98 to your computer and use it in GitHub Desktop.
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
#Combinations | |
# Time complexity: N^K where k = target | |
# Space complexity: K * N^2 | |
def nchoosek(numbers, target, partial=[]) | |
if partial.size == target | |
puts "#{partial}" | |
return | |
end | |
(0...numbers.length).each do |i| | |
n = numbers[i] | |
remaining = numbers.drop(i+1) | |
nchoosek(remaining, target, partial + [n]) # partial + [n] creates a new array | |
end | |
end | |
nchoosek([3,9,8,0,1,2],3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment