Monday 15 February 2010

algorithm - 0/1 Knapsack Dynamic Programming Optimazion, from 2D matrix to 1D matrix -


I need some explanation from Wikipedia, on the part

This solution will be executed In addition to O (NW) time and O (NW) space, if we only use one-dimensional array to store the current optimal values ​​[m] and pass I + 1 times from this array, So every time I write [w] from m [1], we get the same result For Val o (W) space.

To save me in space, I have trouble understanding how to change the 2D matrix in 1D matrix. Apart from this, M [1] every time from M [W] writes [1] every time means (or how it works).

Please provide some examples. Say I have set {V, W} - & gt; Kashmiri = 9 with <(5,4), (6,5), (3,2)}

How does 1D array look?

In many dynamic programming problems, you line 2D table row, where each row depends only on the line that is immediately preceded. In the case of the lid problem, the repetition (from Wikipedia) is the following:

m [i, w] = m [i - 1, w] if w i < / Sub> & gt; W [i, w] = max (m [i - 1, w], i [i - 1, w - w] sub sub i] i ) otherwise

Note that all read from the table when I only fill out the row I come from line I-1; In the table, the previous rows are not actually used. As a result, you can save the space in the 2D table by simply archiving two rows - whatever you are filling with the last line and the filling in that row. You can customize it just by making it a little clever about it, you can optimize it in just one line. Table entries make it less than O (W) (one or two rows and O (W) columns) from O (NW) (O) rows and O (W) columns).

It comes at a price, though. Many DP algorithms do not clearly calculate the solution, but rather fill it in the table instead, then finally pass a second pass to the table so that the optimum answer can be obtained. If you store only one line, you will get the value of the optimal answer, but you probably will not know what should be the optimal answer. In this case, you can read the maximum value that you can fit in the lid, but you do not necessarily be able to recover what you should do to gain that value.

Hope it helps!

No comments:

Post a Comment