当前位置:网站首页>leetcode:730. Count how many different palindrome subsequences can be generated
leetcode:730. Count how many different palindrome subsequences can be generated
2022-07-21 08:55:00 【Oceanstar's study notes】
Title source
Title Description
class Solution {
public:
int countPalindromicSubsequences(string s) {
}
};
title
Similar topics : leetcode:940. How many subsequences with different literals
Recurrence of violence
There are two choices for each character: Yes and no , Finally, judge whether it is a palindrome string
class Solution {
bool isP(string path, int pi){
if(pi == 0){
return false;
}
int L = 0, R = pi - 1;
while (L < R) {
if (path[L++] != path[R--]) {
return false;
}
}
return true;
}
int process(string s, int si, string path, int pi){
if(si == s.length()){
return isP(path, pi) ? 1 : 0;
}
int ans = process(s, si + 1, path, pi);
path[pi] = s[si];
ans += process(s, si + 1, path, pi + 1);
return ans;
}
public:
int countPalindromicSubsequences(string s) {
if(s.empty()){
return 0;
}
string path;
return process(s, 0, path, 0);
}
};
Dynamic programming
For palindromes , Basically, they try to model in scope
therefore , We define dp[i][j] Express :
- from s t r [ i . . . . j ] str[i....j] str[i....j] How many palindromes can be found in all subsequences of , Empty string does not count
- that : The final d p [ 0 ] [ N − 1 ] dp[0][N - 1] dp[0][N−1] That's what we want
Try on the scope , Often go to the beginning of the discussion 、 How to divide the possibilities at the end . There are four possibilities :
- Palindrome subsequence A certain No choice s t r [ i ] str[i] str[i], A certain No choice s t r [ j ] str[j] str[j]
- Palindrome subsequence A certain No choice s t r [ i ] str[i] str[i], A certain choice s t r [ j ] str[j] str[j]
- Palindrome subsequence A certain choice s t r [ i ] str[i] str[i], A certain No choice s t r [ j ] str[j] str[j]
- Palindrome subsequence A certain choice s t r [ i ] str[i] str[i], A certain choice s t r [ j ] str[j] str[j]
Final d p [ i ] [ j ] = a + b + c + d dp[i][j] = a + b + c + d dp[i][j]=a+b+c+d
We can treat a long string as a short string plus two characters around , So there is s[i,j] = s[i] + s [i+1,j-1] + s[j]
, such as : Such as :“bccb” Can be seen as “cc" Add "b”, At this point, let's discuss it according to the situation
(1) If s[i] == s[j]
, Equivalent to we give s[i + 1, j - 1]
Add two identical characters to the left and right , Then we calculate the number of different palindrome sequences
① s [ i + 1 , j − 1 ] s[i+1,j-1] s[i+1,j−1] There are no characters and s[i] equal
- Set the string "bcb", be "bcb" The palindrome subsequence of is :c、bcb 、b、bb( b、c、bb、bcb )
- Set the string "abcba", be :
- It is equivalent to giving "bcb" A new palindrome subsequence can be formed by adding a character to the left and right of the subsequence of ,
- Plus "a"( The character itself is a palindrome subsequence ) and "aa"( Palindrome subsequence of two identical characters )
- So at this time d p [ i ] [ j ] = 2 d p [ i + 1 ] [ j − 1 ] + 2 dp[i][j] = 2dp[i+1][j-1] + 2 dp[i][j]=2dp[i+1][j−1]+2( Of itself 4 individual + A new generation of 4 individual +2 Separately generated )
② s [ i + 1 , j − 1 ] s[i+1,j-1] s[i+1,j−1] There is a character and s[i] equal
- Set the string "bcb", be "bcb" The palindrome subsequence of is : b、c、bb、bcb
- Set the string "cbcbc", Then the palindrome subsequence is :b、c、bb、bcb、cbc、ccc、cbbc、cbcbc、
c、 cc - Suppose one character is equal , The palindrome subsequence of this single character has been recorded before ( Only... Can be added "cc", Cannot add "c")
- So at this time d p [ i ] [ j ] = 2 d p [ i + 1 ] [ j − 1 ] + 1 dp[i][j] = 2dp[i+1][j-1] + 1 dp[i][j]=2dp[i+1][j−1]+1( Of itself 4 individual + A new generation of 4 individual +1 Separately generated )
③ s [ i + 1 , j − 1 ] s[i+1,j-1] s[i+1,j−1] There are two or more characters and s[i] equal
- If there are two or more characters , Then we need to find its location , And delete the palindrome subsequence of repeated calculation , And two separate ones have been calculated before .
- Assuming a string "dabcbad", We add characters to both sides "a"
- Then "a" The characters will match the middle "bcb" Form repeated palindrome subsequences , Because there have been "a" and "bcb" Form palindrome subsequence
(2) if s[i] != s[j], Then we add s[i] and s[j] Can not form palindrome subsequence , It can only be calculated separately
- for instance
- Calculation abb The palindrome subsequence of :a、b、bb
- Calculation ab The palindrome subsequence of :a、b
- Calculation bb The palindrome subsequence of :b、bb
- Look at it , You can find s[L+1][R-1] It was calculated repeatedly
- Calculation abb The palindrome subsequence of :a、b、bb
in summary , The equation of state transfer is :
class Solution {
public:
int countPalindromicSubsequences(string S) {
int strSize = S.size(), M = 1e9 + 7;
//dp[i][j] It means S[i, j] The number of different palindrome subsequences in this string
vector<vector<int>> dp(strSize, vector<int>(strSize, 0));
// initialization , A string of length is also a result
for (int i = 0; i < strSize; ++i) {
dp[i][i] = 1;
}
// Start dynamic planning
for (int i = strSize - 2; i >= 0; --i){
for (int j = i + 1; j < strSize; ++j){
// The upper two floors for Loops are used to enumerate intervals [i, j],i Used to determine the starting point of the interval ,j Determine the end of the interval , And the length of the interval is determined by 2 Gradually increase
if (S[i] == S[j]) {
//left Used to find and S[i] The first subscript at the same left end ,right Used to find and S[i] The first subscript at the same right end
int left = i + 1, right = j - 1;
while (left <= right && S[left] != S[i]) {
++left;
}
while (left <= right && S[right] != S[i]) {
--right;
}
if (left > right) {
// There is no and S[i] Same letter , for example "aba" This situation
// among dp[i + 1][j - 1] Is the number of palindrome subsequences in the middle part , Because all subsequences in the middle can exist alone , You can also wrap letters on the outside a, So it's in pairs , To ride 2.
// Add 2 The reason is the outer "a" and "aa" It should also be statistically
dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
}
else if (left == right) {
// There is only one and S[i] Same letter , Namely "aaa" This situation ,
// Multiply by 2 Part of the reason is the same as the above ,
// Add 1 The reason is a single letter "a" The situation of has been calculated in the middle part , The outer layer can only be added "aa" 了 .
dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
}
else {
// There are at least two and S[i] Same letter , Namely "aabaa" This situation ,
// Multiply by 2 Part of the reason is the same as the above , To subtract left and right The reason for the number of subsequences in the middle part is that it has been calculated twice , Reduce the extra .
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1];
}
}
else {
//dp[i][j - 1] + dp[i + 1][j] Here we calculate dp[i + 1][j - 1] Two times
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
}
dp[i][j] = (dp[i][j] < 0) ? dp[i][j] + M : dp[i][j] % M;
}
}
return dp[0][strSize - 1];
}
};
边栏推荐
- labelme voc数据格式转yolo txt数据格式
- 【漏洞复现】Apache Log4j2 远程代码执行漏洞
- 分布式事务
- 败走IPO的年轻人
- Clip based pornographic image recognition; The latest ml course collection of tubing; Write shell pipes interactively; Incremental perception data set of robot warehouse environment; Latest AI paper |
- MLX90640 红外热成像传感器测温模块开发笔记(一)
- Win系统运维
- Pycharm退出pytest模式(run pytest in模式)
- 罗敏成不了董宇辉
- Hj14 string sorting
猜你喜欢
Redis - CLUSTER命令中集群管理命令详解
Android kotlin uses arouter componentized routing and datastore to save data instead of SharedPreferences
这几所院校会压分!请注意!
App automated test -3 Appium element positioning and waiting
Klocwork部署的安全最佳实践
ython中if __name__ == ‘__main__‘:的作用和原理
论文写作全攻略|一篇学术科研论文该怎么写
How to write the docker cleaning cache script
关于let变量提升的问题
MySQL Foundation (multi table query, transaction)
随机推荐
MySQL Basics (functions and constraints)
Netease game Flink SQL platform practice
How to solve the RSA public key not find problem in Navicat
自己整理一些散的知识点
MLX90640 红外热成像传感器测温模块开发笔记(一)
js 常见的replace()方法案例
III Uni app configuration file [global configuration, bottom navigation bar configuration, file configuration]
[vulnerability recurrence] Apache log4j2 Remote Code Execution Vulnerability
Redis - 管理工具 redis-cli 详解
In microservices * IML file deletion
HJ13 句子逆序
去河南投资,VC很犹豫
Hj18 identifies valid IP addresses and masks and makes classification statistics
记录封装组件和项目中防抖的使用
三维点云课程(五)——深度学习
Rsync combined with inotify to realize real-time file synchronization (I)
全网追杀“钱包刺客”
MySQL基礎(多錶查詢、事務)
Redis - detailed explanation of redis cli management tool
Can the active data guard standby database run query operations or read-only applications?