Chapter 2 - Implicit Tree and Backtracking

We can also treat lists as a tree!

Permal Algorithm

In CS310 we are familiar with the permal algorithm, in reality, this is just backtracking. Backtracking is the idea that we can diverge lists to a tree, and if something doesn't work out we can end the path of the tree and try the other path of the tree.

Permall:

global Buffer[1..n];
procedure PermDriver(n;;);
    output: Prints all n! permutations of 1 through n;
    for i ← 1 to n do Buffer[i] ← i endfor; { initializes Buffer[1..n] }
    Permall(n)
end_PermDriver;

global n; { just to keep the parameter list less cluttered }
procedure Permall(h;;); { h = tree_height of current vertex }
    local i; { remember which child to process next in each iteration }
    if h equals zero then print Buffer[1..n] endif;
    for i ← 1 to h do { simulates: foreach child i of the current vertex at this height do }
        swap Buffer values in location h and location i;
        Permall(h - 1); { recurse }
        swap Buffer values in location h and location i
    endfor { <- this swap is proven to restore Buffer perfectly by induction starting with height 1. }
end_Permall;

Applications of Permall (Backtracking)

How do I get all the permutation of a list?

We can literally copy and modify from the permal!

Permutation is just a rearrangement of a list, therefore it cannot have duplicate values. Under the for loop, you can think of .append and .pop as the swapping buffer values in permall. If the length of the current array is the same length as the input array, we have found a possible permutation so we can add it to our result.

How do I get the subsets of a list?

We can also use permall and tweak it

This is how we can understand the code. Start off from the for loop, we have to start from the starting index to the length of nums. We can update the starting index by passing into i + 1 so that this is the starting index for the next recursion. Because permall treats everything as a tree, we don't need a base case we just need to add the current path to the result since it will do a DFS.

Coin Problem? Suppose we have a list of coins that we can use and a target we want to add the coins up to, how do I get the least amount of coins?

Subset Sum

Last updated