Total number of palindromic subsequences in a string

后端 未结 3 1822
你的背包
你的背包 2021-01-31 12:47

The question is like this--

For every string given as input, you need to tell the number of subsequences of it that are palindromes (need not necessarily be distinct). N

3条回答
  •  灰色年华
    2021-01-31 13:31

    Here's a horrible O(n^4) solution:

    Every palindromic subsequence begins at some position i and ends at some position j >= i such that x[i] = x[j], and its "interior" (all characters except the first and last) is either empty or a palindromic subsequence of x[i+1 .. j-1].

    So we can define f(i, j) to be the number of palindromic subsequences beginning at i and ending at j >= i. Then

    f(i, j) = 0 if x[i] != x[j]
    f(i, i) = 1 (i.e. when j = i)
    f(i, j) = 1 + the sum of f(i', j') over all i < i' <= j' < j otherwise
    

    [EDIT: Fixed to count palindromic subsequences of length <= 2 too!]

    Then the final answer is the sum of f(i, j) over all 1 <= i <= j <= n.

    The DP for this is O(n^4) because there are n^2 table entries, and computing each one takes O(n^2) time. (It's probably possible to speed this up to at least O(n^3) by making use of the fact that x[i] != x[j] implies f(i, j) = 0.)

提交回复
热议问题