2-D Dynamic Programming Two strings
570. Count Palindromic Subsequences
You are given a string s. Count its subsequences that are palindromes.
A subsequence is what is left after deleting some letters of s, without changing the order of the rest.
Its letters do not have to sit next to each other. A palindrome reads the same forwards and backwards. A
single letter is a palindrome. The empty subsequence does not count.
Subsequences are told apart by the positions they use, not by the word they spell. In "aa", the first a
and the second a are two different subsequences, so the answer is 3: a, a and aa.
The count can be very large, so return it modulo 109 + 7.
Example 1
Input: s = "abab"
8Explanation: The four single letters, aa (indexes 0 and 2), bb (1 and 3), aba (0, 1, 2) and bab (1, 2, 3).
Example 2
Input: s = "aaa"
7Explanation: Every one of the 7 non-empty choices of positions spells a palindrome. aa alone appears 3 times: indexes
0 and 1, 0 and 2, and 1 and 2.
Example 3
Input: s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
147483633Explanation: s has 31 copies of a, so all 231 − 1 = 2147483647 non-empty subsequences are palindromes.
Modulo 109 + 7 that is 147483633.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 3000sholds only lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.