Lab 09 - Backtracking
Last updated
Last updated
Slides:
Construct a cumulative frequency table.
It seems (erroneously) that recursion is always about "going backwards". but it is not always the case.
A problem-solving paradigm (Usually used in AI):
Suppose we have an initial state S.
Our goal is to find all states where a terminating condition p holds.
Upon entering each current state X, we first check if p is true. If it is, we collect X as a valid result.
Else, we explore the actions that can be performed at state X to transition to a different state Y.
For each new state Y generated this way, we enter it and repeat the process.
After exhausting all possible actions, we return to the previous state.
And the steps can be summarized as:
Define goal(S)
Define condition for goal(S)
Define state representation
Define actions and transitions (Usually it is recursion)
Invoke function with initial state
Backtracking is searching by brute force.
The difficult part is for us to find "initial state S, goal, terminating condition, actions that can be performed to transition, return to the previous state".
We start our sequence and number of digits k = 0
At every stage, check: is k = n? (This is our terminating condition)
If yes, then this is a valid sequence, we will print it and return (Collect a valid result and backtrack to the previous state)
If no, then we have 2 choices to proceed to the next stage:
Append 0 to the end of s
; or
Append 1 to the end of s
However, this code will miss printing the digits infront in the after backtracking. There are two methods to solve this:
Taking the Depth-First-Search as an example. Given that two vertices v and u, we wish to determine whether they are connected by a path.
Identify the following
Current Stage: The current vertex x (initially v)
Terminating Condition: x=u
State Transitions: Move to any unvisited neighbour of x
A genius way to solve this problem is to use combinatorics! Legit genius! But only implementing directly is not correct! (The factorial will easily exceed the space limit of long
). Try the step-by-step solution.
We can practice this kind of thinking using one of the past year PE questions .
Change the representation to whole number. See
Use an array to store the appended characters. See