Sub topic 2
Generating All Permutations
This chapter assumes you know the choose-explore-unchoose template, why results must be copied with path[:], and the subset generator from the previous chapter. It applies that template to permutations and combinations, then shows how to cut the search short and how to skip duplicate results.
Permutations with a Used Array
In a subset, every element after the current one is a valid next choice. In a permutation, any unused element is a valid next choice, so the loop always starts at index 0. A used array records which elements the current path already holds. The path and the marks must both be restored after each recursive call.
def permutations(nums):
result = []
path = []
used = [False] * len(nums)
def backtrack():
if len(path) == len(nums):
result.append(path[:])
return
for i in range(len(nums)):
if used[i]:
continue
used[i] = True
path.append(nums[i])
backtrack()
path.pop()
used[i] = False
backtrack()
return result
print(permutations([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]A common bug is forgetting used[i] = False. Once a mark stays set, the branches that follow can no longer pick that element, and permutations go missing without any error.
Combinations and Target-Sum Search
Combination sum asks for every multiset of candidates that adds up to a target, with each candidate allowed more than once. The recursion passes i rather than i + 1, so the same candidate can be picked again. Because start never moves backward, [2, 3] and [3, 2] cannot both be produced.
Pruning: Abandoning Hopeless Branches Early
Pruning means stopping a branch as soon as it cannot lead to a valid answer. If the candidates are sorted, the first one that exceeds the remaining sum proves that every later one does too, so break drops the rest of the loop at once.
def combination_sum(candidates, target):
# Assumes candidates are distinct positive integers; each may be reused.
candidates = sorted(candidates)
result = []
path = []
def backtrack(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break # sorted input: every later candidate is too large too
path.append(c)
backtrack(i, remaining - c)
path.pop()
backtrack(0, target)
return result
print(combination_sum([2, 3, 6, 7], 7))
# [[2, 2, 3], [7]]Avoiding Duplicate Results
When the input repeats a value, such as [1, 2, 2], the two 2s would start identical branches and produce the same subset twice. The fix is to sort the input and then skip any value that equals the one before it at the same tree level. The condition i > start still lets the second 2 be used deeper in the tree, which is why [2, 2] appears.
def subsets_with_dup(nums):
nums = sorted(nums)
result = []
path = []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue # skip a repeated value at the same tree level
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return result
print(subsets_with_dup([1, 2, 2]))
# [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]Exercise
In combination_sum, what changes in the output if backtrack(i, remaining - c) is replaced with backtrack(i + 1, remaining - c)?
Show answer
Each candidate can then be used at most once. For [2, 3, 6, 7] with target 7, the result becomes [[7]], because [2, 2, 3] needed 2 twice.
Exercise
Why does subsetswithdup check i > start instead of i > 0?
Show answer
The check i > 0 would also skip a repeated value when it is the first choice at a deeper level. That would lose valid results such as [2, 2]. The check i > start skips repeats only among siblings at the same level.