今天是第五十七天,也是动态规划的最后一天
class Solution { public int countSubstrings(String s) { int n = s.length(); int res = 0; boolean[][] dp = new boolean[n][n]; for (int j = 0; j < n; j++) { for (int i = 0; i <= j; i++) { if (s.charAt(i) == s.charAt(j)) { if (j - i < 3) { dp[i][j] = true; } else { dp[i][j] = dp[i + 1][j - 1]; } } else { dp[i][j] = false; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dp[i][j]) res++; } } return res; } }
分三种情况看下标i与j的和的差,如果为0则true,为1则false,大于1则通过前后的数组来判断。
class Solution { public int longestPalindromeSubseq(String s) { int n = s.length(); int[][] dp = new int[n][n]; for(int i =0; i<n; i++){ dp[i][i]= 1; } for(int i = n-1; i>=0; i--){ for(int j = i+1; j<n; 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][n-1]; } }dp[i][j] 依赖于dp[i+1][j]和dp[i+1][j-1]
今天是动态规划的最后一天,动态规划的好多题很容易混淆,需要重复做!加油!!!
标签:int,代码,随想录,第五十七,动态,规划,dp From: https://www.cnblogs.com/catSoda/p/16971431.html