Skip to content

Instantly share code, notes, and snippets.

@evidanary
Created June 16, 2017 21:49
Show Gist options
  • Save evidanary/e8f702d6ca504c708ff0ddaa19412a98 to your computer and use it in GitHub Desktop.
Save evidanary/e8f702d6ca504c708ff0ddaa19412a98 to your computer and use it in GitHub Desktop.
#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