动态规划

动态规划

Jason Lv3

647. 回文子串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int countSubstrings(String s) {
char[] chars = s.toCharArray();
int len = chars.length;
boolean[][] dp = new boolean[len][len];
int result = 0;
for (int i = len - 1; i >= 0; i--) {
for (int j = i; j < len; j++) {
if (chars[i] == chars[j]) {
if (j - i <= 1) { // 情况一 和 情况二
result++;
dp[i][j] = true;
} else if (dp[i + 1][j - 1]) { //情况三
result++;
dp[i][j] = true;
}
}
}
}
return result;
}
}

516. 最长回文子序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int longestPalindromeSubseq(String s) {
int len = s.length();
int[][] dp = new int[len+1][len+1];
for(int i=len-1;i>=0;i--){
dp[i][i]=1;
for(int j=i+1;j<len;j++){
if(s.charAt(i)==s.charAt(j)) dp[i][j]=dp[i+1][j-1]+2;
else{
dp[i][j]=Math.max(dp[i+1][j],dp[i][j-1]);

}
}
}
return dp[0][len-1];
}
}
  • Title: 动态规划
  • Author: Jason
  • Created at : 2023-09-20 14:40:13
  • Updated at : 2023-09-20 14:45:27
  • Link: https://xxxijason1201.github.io/2023/09/20/LeetCode/DP/
  • License: This work is licensed under CC BY-NC-SA 4.0.
 Comments