Backtracking
It's usually useful to think of backtracking problem as a depth-first-search problem in a tree. Construct the right tree for different problems.
Use recursion to write backtracking program.
For storing each solution, there are usually two ways:
Initialize a list (empty or with a given length) before running the helper function, update elements in the list when we process the backtracking. When a path is finished, append this solution to the output.
Add a parameter in the helper function to store the solution we have seen so far. Update this parameter when we process. When a path is finished, append this parameter to the output.
Question 78_Subsets illustrates the two ways.
Note:
difference between backtracking and depth first search
Backtracking is a more general purpose algorithm. Depth-First search is a specific form of backtracking related to searching tree structures.
Backtracking is DFS for implicit tree, while DFS is backtracking without pruning.
Last updated