Remember to label the horizontal and vertical axes with substrings of the two given strings.
What is the length of the longest common subsequence?
f(1)= 1; f(2)= 1; f(3)= 1; f(4)= 3; f(5)= 5;
f(n)= f(n-1) + 3*f(n-5) for n >5.
+---+---+---+---+---+
0 | 6 | 7 | 4 | 7 | 8 |
+---|---|---|---|---+
1 | 7 | 6 | 1 | 1 | 4 |
+---|---|---|---|---+
2 | 3 | 5 | 7 | 8 | 2 |
+---|---|---|---|---+
3 | 2 | 6 | 7 | 0 | 2 |
+---|---|---|---|---+
4 | 7 | 3 | 5 | 6 | 1 |
+---+---+---+---+---+
0 1 2 3 4
Each of the numbers in the squares represents an amount of money in dollars. A counter is first placed on the top left square.
The player's objective is to move the counter vertically,
or diagonally (always downwards)
one square per move, in order to reach the
bottom row. Thus if he is at position (i,j), then his possible moves are to move the counter to (i+1, j-1), (i+1,j) or (i+1, j+1).
However, there is a snag: every time the counter lands on a square, the money is removed from that square on the board. When he reaches the bottom row, he is allowed to keep the remaining money on the board. Thus his objective is to maximise his winnings, which translates to finding a path whose total worth is as small as possible.
An obvious recursive solution to calculate the minimimum path value is as follows
int minCost(int i, int j) {
if (i== 4) return c[i][j];
else
return min( minCost(i+1, j), minCost(i+1, j-1), minCost(i+1, j+1) ) + c(i, j);
}
where "min" is thw function that computes the minimum of its inputs. As with other examples we've seen, this is not very efficient, since the same values are recomputed repeatedly.
Use the ideas of dynamic programming to use a table LookUp[i][j], which stores the cost of the minimum path value from position (i, j) on the board to the bottom row (i.e. i==4). The following hints should help you.
a
/ \
b c
/ \ / \
d e f g
/ / / \
h i j k
For each of inorder, preorder and postorder traversals, state the order of the nodes printed.
All enquiries to Annabelle McIver