730. Count Different Palindromic Subsequences
Problem description:
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
.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequences a1, a2, ...
and b1, b2, ...
are different if there is some i
for which ai != bi
.
Example 1:
1 | Input: s = "bccb" |
Example 2:
1 | Input: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba" |
Constraints:
1 <= s.length <= 1000
s[i]
is either'a'
,'b'
,'c'
, or'd'
.
Solution:
The string only contains 'a'
, 'b'
, 'c'
, or 'd'
.
dfs+ memo to calculate
find palindrome in substrings and store the count in memo
try to find the occurance of left and right index for “abcd”
if left == right
: no same character in the substring, additional is a
, which is 1+ dfs(substring)
if left != right
: there could be a
, aa
, a*a
, count for this is 2 + dfs(substring)
1 | class Solution: |
time complexity: $O(n^2)$
space complexity: $O(n^2)$
reference:
related problem: