Skip to content

Commit e1744d3

Browse files
committed
Add solution #730
1 parent 3af011a commit e1744d3

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@
553553
726|[Number of Atoms](./0726-number-of-atoms.js)|Hard|
554554
728|[Self Dividing Numbers](./0728-self-dividing-numbers.js)|Easy|
555555
729|[My Calendar I](./0729-my-calendar-i.js)|Medium|
556+
730|[Count Different Palindromic Subsequences](./0730-count-different-palindromic-subsequences.js)|Hard|
556557
733|[Flood Fill](./0733-flood-fill.js)|Easy|
557558
735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium|
558559
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 730. Count Different Palindromic Subsequences
3+
* https://leetcode.com/problems/count-different-palindromic-subsequences/
4+
* Difficulty: Hard
5+
*
6+
* Given a string s, return the number of different non-empty palindromic subsequences in s.
7+
* Since the answer may be very large, return it modulo 109 + 7.
8+
*
9+
* A subsequence of a string is obtained by deleting zero or more characters from the string.
10+
*
11+
* A sequence is palindromic if it is equal to the sequence reversed.
12+
*
13+
* Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.
14+
*/
15+
16+
/**
17+
* @param {string} s
18+
* @return {number}
19+
*/
20+
var countPalindromicSubsequences = function(s) {
21+
const MOD = 1e9 + 7;
22+
const dp = new Array(s.length).fill().map(() => {
23+
return new Array(s.length).fill(0);
24+
});
25+
26+
for (let i = 0; i < s.length; i++) {
27+
dp[i][i] = 1;
28+
}
29+
30+
for (let len = 2; len <= s.length; len++) {
31+
for (let start = 0; start + len <= s.length; start++) {
32+
const end = start + len - 1;
33+
const charStart = s[start];
34+
const charEnd = s[end];
35+
36+
if (charStart !== charEnd) {
37+
dp[start][end] = (dp[start + 1][end] + dp[start][end - 1] - dp[start + 1][end - 1]) % MOD;
38+
} else {
39+
let left = start + 1;
40+
let right = end - 1;
41+
42+
while (left <= right && s[left] !== charStart) left++;
43+
while (left <= right && s[right] !== charStart) right--;
44+
45+
if (left > right) {
46+
dp[start][end] = (2 * dp[start + 1][end - 1] + 2) % MOD;
47+
} else if (left === right) {
48+
dp[start][end] = (2 * dp[start + 1][end - 1] + 1) % MOD;
49+
} else {
50+
dp[start][end] = (2 * dp[start + 1][end - 1] - dp[left + 1][right - 1]) % MOD;
51+
}
52+
}
53+
54+
if (dp[start][end] < 0) dp[start][end] += MOD;
55+
}
56+
}
57+
58+
return dp[0][s.length - 1];
59+
};

0 commit comments

Comments
 (0)