Skip to content

Instantly share code, notes, and snippets.

@okoye
Created August 10, 2014 22:21
Show Gist options
  • Save okoye/168f5ae70e57043fb9b3 to your computer and use it in GitHub Desktop.
Save okoye/168f5ae70e57043fb9b3 to your computer and use it in GitHub Desktop.
python solution to the subset-sum problem. A bruteforce approach
def subsetsum(numbers, target):
size = 1
subsets = []
while size <= len(numbers):
for combination in combinations(numbers, size):
if sum(combination) == target:
subsets.append(combination)
size += 1
return subsets
def combinations(numbers, size):
if len(numbers) <= 0 or size <= 0:
yield []
else:
for index, number in enumerate(numbers):
for combination in combinations(numbers[index+1:], size-1):
yield [number]+combination
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment