I am not getting idea on the problem of dynamic programming. I am posting the link of question. Someone please help. Thnaks in advamce.Here is the link
I am not getting idea on the problem of dynamic programming. I am posting the link of question. Someone please help. Thnaks in advamce.Here is the link
| # | User | Rating |
|---|---|---|
| 1 | Benq | 3676 |
| 2 | Kevin114514 | 3659 |
| 3 | jiangly | 3640 |
| 4 | turmax | 3450 |
| 5 | tourist | 3382 |
| 6 | strapple | 3360 |
| 7 | Um_nik | 3354 |
| 8 | squareOf105 | 3348 |
| 9 | maroonrk | 3312 |
| 10 | idontwannadothis…e | 3191 |
| # | User | Contrib. |
|---|---|---|
| 1 | Qingyu | 155 |
| 2 | nik_exists | 151 |
| 3 | maspy | 149 |
| 4 | AmShZ | 145 |
| 5 | Um_nik | 143 |
| 6 | Errichto | 139 |
| 7 | BledDest | 136 |
| 8 | adamant | 134 |
| 9 | maroonrk | 132 |
| 10 | cry | 130 |
| Name |
|---|



Here is my idea for O(N2) dynamic programming solution (got AC):
Let our state be:
F[L][R] = the minimum amount of characters to insert to make the substring SLSL + 1...SR a palindrome.
Obviously the answer would be F[1][n]. Now let's come up with a recursive formula:
Suppose that we are trying to find the answer for some F[L][R]. We can see that at least one of the following three cases will always be true for any solution:
1) We add a character to the end to match SL — in that case, after that one move, we end up trying to make SL + 1...SR a palindrome. So the outcome of this case is F[L + 1][R] + 1.
2) We add a character to the beginning to match SR — in that case, after that one move, we end up trying to make SL...SR - 1 a palindrome. So the outcome of this case is F[L][R - 1] + 1
3) We match SL with SR. This is only possible if they are equal and in that case we have the outcome of F[L + 1][R - 1]
This gives us a simple formula:
F[L][R] = MIN(F[L + 1][R] + 1, F[L][R - 1] + 1) for SL ≠ SR
F[L][R] = MIN(F[L + 1][R] + 1, F[L][R - 1] + 1, F[L + 1][R - 1]) for SL = SR
Base cases are for R ≤ L, F[L][R] = 0
The complexity is O(N2) for both time and memory. Hope that helps :)