[LeetCode]Count Different Palindromic Subsequences

题目描述:

LeetCode 730. Count Different Palindromic Subsequences

Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7.

A subsequence of a string S is obtained by deleting 0 or more characters from S.

A sequence is palindromic if it is equal to the sequence reversed.

Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i.

Example 1:

Input: 
S = 'bccb'
Output: 6
Explanation: 
The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.

Example 2:

Input: 
S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
Output: 104860361
Explanation: 
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.

Note:

  • The length of S will be in the range [1, 1000].
  • Each character S[i] will be in the set {'a', 'b', 'c', 'd'}.

题目大意:

求字符串S的回文子序列的个数

解题思路:

记忆化搜索(Search + Memoization)

Python代码:

class Solution(object):
    def countPalindromicSubsequences(self, S):
        """
        :type S: str
        :rtype: int
        """
        size = len(S)
        next = [{k : -1 for k in 'abcd'} for x in range(size + 1)]
        prev = [{k : -1 for k in 'abcd'} for x in range(size + 1)]
        for x in range(size):
            for k in 'abcd':
                if S[x] == k: prev[x][k] = x
                else: prev[x][k] = prev[x - 1][k]

        for x in range(size - 1, -1, -1):
            for k in 'abcd':
                if S[x] == k: next[x][k] = x
                else: next[x][k] = next[x + 1][k]

        dmap = [[0] * (size + 1) for x in range(size + 1)]

        def solve(i, j):
            if i > j: return 0
            if dmap[i][j]: return dmap[i][j]
            ans = 0
            for k in 'abcd':
                ii, jj = next[i][k], prev[j][k]
                if ii < 0: continue
                if ii < jj: ans += 1
                if ii <= j: ans += solve(ii + 1, jj - 1) + 1
            dmap[i][j] = ans % (10 ** 9 + 7)
            return dmap[i][j]

        return solve(0, size - 1)

 

本文链接:http://bookshadow.com/weblog/2017/11/20/leetcode-count-different-palindromic-subsequences/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论