daiict's blog

By daiict, history, 8 years ago, In English

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

Tags #dp
  • Vote: I like it
  • -5
  • Vote: I do not like it

»
8 years ago, # |
Rev. 3   Vote: I like it +6 Vote: I do not like it

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 :)