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:
1 | Input: |
Example 2:
1 | Input: |
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'}
.
分析
https://www.youtube.com/watch?v=UjiFFYU3EKM
$dp[i][j]$ 表示字符串 $s[i…j]$ 所包含的不重复的回文子序列的数量。
当 $s[i] \neq s[j]$ 时,$dp[i][j] = dp[i+1][j] + d[i][j-1] - dp[i+1][j-1]$
当 $s[i] == s[j]$ 时,$l$ 表示从 $s[(i+1) … j]$ 中,最左边使 $s[l] == s[i]$ 的下标;$r$ 表示从 $s[i … (j-1)]$ 中,最左边使 $s[r] == s[j]$ 的下标;
- $l < r$ 时,$dp[i][j] = 2*dp[i+1][j-1]-dp[l+1][r-1] $
- $l == r$ 时,$dp[i][j] = 2*dp[i+1][j-1] + 1$
- $l > r$ 时,$dp[i][j] = 2*dp[i+1][j-1] + 2$
代码
1 | class Solution { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/04/05/leetcode-730/
License: 知识共享署名-非商业性使用 4.0 国际许可协议