3 ms·
No longest common subsequence? Try that and then make it use O(n) memory instead of the O(n^2) of the simple dynamic programming algorithm.
by jules 17y ago
No longest common subsequence? Try that and then make it use O(n) memory instead of the O(n^2) of the simple dynamic programming algorithm.
- baddox 17y agoMaybe that and rod-cutting were left out because their solutions are in all the books. How do you get it to use O(n) space? I remember the simple solution was to build a matrix bottom-up, the matrix of course being of size n^2. Do you get constant space just by throwing away non-optimal subproblems and adding a predecessor field to each node (a node being an individual letter)?
- kmak 17y agoTypically the way that optimization is you only need the subproblem solution from the previous row, so the rows before that you can ignore (and thrown away) by keeping only 2n entries. This assumes you don't need to reconstruct the path though.
- jules 17y agoYes, something like that. With the standard algorithm you compute a matix where each entry (i,j) in the matrix gets computed from entries (i-1,j),(i,j-1),(i-1,j-1). If you compute the matrix row-by-row then you only need to store two rows, because the next row only depends on the current row. You can reduce the cost from storing two rows (2n entries) to one row (n entries) by rewriting it in-place. You're right that you'd store the solution string in a linked list, because they have O(1) non-destructive append. Or maybe there's another smarter and faster scheme than a linked list? Edit: oh, you could just use an array for each column, and append the letter in-place. Or does this use more space because the prefixes are not shared among the different columns?