Slide 11
Slide 11 text
def find_all_permutations(nums: List[Int]) -> List[List[Int]]:
res = []
backtrack(nums, [], set(), res)
return res
def backtrack(
nums: List[Int],
candidate: List[Int],
used: Set[Int],
res: List[List[Int]]
) -> None:
# If the current candidate is a complete
# permutation, add it to the result.
if len(candidate) == len(nums):
res.append(candidate[:])
return
for num in nums:
if num not in used:
# Add 'num' to the current permutation and mark it as used.
candidate.append(num)
used.add(num)
# Recursively explore all branches using
# the updated permutation candidate.
backtrack(nums, candidate, used, res)
# Backtrack by reversing the changes made.
candidate.pop()
used.remove(num)
@alexxubyte
Alex Xu
@shaungunaw
Shaun Gunawardane
numbers to generate permutations with
permutation grown so far
numbers used up so far
permutations generated so far
Here is the Python code for the imperative procedural
solution to the combinatorial problem of computing the
permutations of a list of numbers.
The authors solve the problem using a recursive backtrack
function which, for each number not yet added to a
permutation that is currently being generated, adds the
number to the permutation and then calls itself recursively.
When the recursive call returns, the function backtracks by
removing the number from the permutation being generated.
The recursion base case is reached when the permutation
being generated is complete, at which point it is added to a
running result accumulator.
The reader is walked through a series of diagrams visualising
the individual steps of the recursive backtracking process.
See the diagram below for a simplified, compressed
representation of all the steps.
[]
[4] [6]
[4,5] [4,6]
[4,5,6][4,6,5]
choose
4
choose
6
choose
5
choose
6
choose
6
choose
5
[5]
[5,4] [5,6]
[5,4,6][5,6,4]
choose
4
choose
6
choose
6
choose
4
[6,4] [6,5]
[6,4,5][6,5,4]
choose
4
choose
5
choose
5
choose
4
choose
5
nums candidate used
[4,5,6] [] {}
[4,5,6] [4] {4}
[4,5,6] [4,5] {4,5}
[4,5,6] [4,5,6] {4,5,6}
[4,5,6] [4,6] {4,6}
[4,5,6] [4,6,5] {4,6,5}
[4,5,6] [5] {5}
β¦ β¦ β¦
for num in [4,5,6]:
if num not in {}
for num in [4,5,6]:
if num not in {4}
for num in [4,5,6]:
if num not in {4,5}