For each item, try including it, then try leaving it out. Undo each choice on the way back. The result is every subset.
Python · intermediate · 9 min · 42 steps · free
def subsets(items):
result = []
current = []
def choose(i):
if i == len(items):
result.append(current[:])
return
current.append(items[i])
choose(i + 1)
current.pop()
choose(i + 1)
choose(0)
return result
print(subsets(['a', 'b']))subsets(). Its body does not run yet: it runs each time the function is called.subsets(), with items = ['a', 'b']. It gets its own names.result is created and points to a new list: [].current is created and points to a new list: [].choose(). Its body does not run yet: it runs each time the function is called.choose(), with i = 0, choose = function choose(), current = [], items = ['a', 'b'] and result = []. It gets its own names.i == len(items) is false, so the block under it is skipped.choose() #2, with i = 1, choose = function choose(), current = ['a'], items = ['a', 'b'] and result = []. It gets its own names.i == len(items) is false, so the block under it is skipped.current points to.choose() #3, with i = 2, choose = function choose(), current = ['a', 'b'], items = ['a', 'b'] and result = []. It gets its own names.i == len(items) is true, so the block under it runs.choose() #3 has finished, so its names are gone.i == len(items) is true, so the block under it runs.result points to.choose() #3 has finished, so its names are gone.choose() #2 has finished, so its names are gone.current points to.choose() #2, with i = 1, choose = function choose(), current = [], items = ['a', 'b'] and result = [a list, a list]. It gets its own names.i == len(items) is false, so the block under it is skipped.current points to.choose() #3, with i = 2, choose = function choose(), current = ['b'], items = ['a', 'b'] and result = [a list, a list]. It gets its own names.i == len(items) is true, so the block under it runs.result points to.choose() #3 has finished, so its names are gone.current points to.choose() #3, with i = 2, choose = function choose(), current = [], items = ['a', 'b'] and result = [a list, a list, a list]. It gets its own names.i == len(items) is true, so the block under it runs.result points to.choose() #3 has finished, so its names are gone.choose() #2 has finished, so its names are gone.choose() has finished, so its names are gone.subsets() has finished, so its names are gone. It prints [['a', 'b'], ['a'], ['b'], []].current itself instead of a copy, so every saved subset changes laterAnswer: 1024. 2¹⁰.
Answer: To save a copy
← Dijkstra's Shortest Paths · Dynamic Programming: Memo and Table →