Count Different Palindromic Subsequences — LeetCode 730 Python Solution
- Problem
- #730
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.
Example
- Input
- s = "bccb"
- Output
- 6
- Explanation
- The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Python solution
class Solution:
def countPalindromicSubsequences(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
dp = [[[0] * 4 for _ in range(n)] for _ in range(n)]
for i, c in enumerate(s):
dp[i][i][ord(c) - ord('a')] = 1
for l in range(2, n + 1):
for i in range(n - l + 1):
j = i + l - 1
for c in 'abcd':
k = ord(c) - ord('a')
if s[i] == s[j] == c:
dp[i][j][k] = 2 + sum(dp[i + 1][j - 1])
elif s[i] == c:
dp[i][j][k] = dp[i][j - 1][k]
elif s[j] == c:
dp[i][j][k] = dp[i + 1][j][k]
else:
dp[i][j][k] = dp[i + 1][j - 1][k]
return sum(dp[0][-1]) % modComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 730. Count Different Palindromic Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 730. Count Different Palindromic Subsequences?
- LeetCode 730. Count Different Palindromic Subsequences is rated Hard on LeetCode.
- What topics does LeetCode 730. Count Different Palindromic Subsequences cover?
- LeetCode 730. Count Different Palindromic Subsequences is tagged String and Dynamic Programming on LeetCode.