Please give me efficient and easy way that I can covert recursive dp to iterative dp. You can suggest me blogs or video tutorial. It will be very helpful.
Thanks in advance.
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 166 |
2 | maomao90 | 163 |
2 | Um_nik | 163 |
4 | atcoder_official | 161 |
5 | adamant | 160 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | nor | 153 |
9 | Dominater069 | 153 |
Please give me efficient and easy way that I can covert recursive dp to iterative dp. You can suggest me blogs or video tutorial. It will be very helpful.
Thanks in advance.
Name |
---|
Why write recursive dp in the first place? It's so confusing to write
I learned dp in recursive way in primary level but now I think I need to move in iterative way for time and also memory optimization. But I found recursive solution for most of the problem, so I need now how can I think in iterative way.
First, writing recursive dp is slower but its necessary for some problems. Sometimes you just can't do it.
Now answering your question, it's mainly about what states need to be calculated before you can safely calculate the current one. For example if you're doing a 2d knapsack like dp[i][j] — being i the item and j the value — for each item you need to calculate the items that go before it first, so you iterate through i from 1 to n. At that point, it's just the same as a recursive dp, but you are accessing the array instead of calling a function.
In this case it's simple (actually most cases are simple) but sometimes you will need to think a little bit. For example when dp[i][j] means a segment from i to j and it depends on dp[i][k] and dp[k][j] (that is, a dp of intervals where to calculate it you use the dp of smaller intervals), you will need to iterate through the length of the segment instead of something else.
you can always use a stack like data structure to convert any recursive function to an iterative function