1143.最长公共子序列
java
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
//确定dp数组(dp table)以及下标的含义
/**
dp[i][j]:长度为[0, i - 1]的字符串text1与长度为[0, j - 1]的字符串text2的最长公共子序列为dp[i][j]
*/
int[][] dp = new int[text1.length() +1][text2.length()+1];
/**
初始化:dp[i][0] = dp[0][j] = 0;
*/
for(int i = 1;i<=text1.length();i++){
char char1 = text1.charAt(i-1);
for(int j = 1;j<=text2.length();j++){
char char2 = text2.charAt(j-1);
if(char1 == char2){
dp[i][j] = dp[i-1][j-1] +1;
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[text1.length()][text2.length()];
}
}
1035.不相交的线
java
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
/**
此题和公共子序列题意相同,表达不同
*/
int[][] dp = new int[nums1.length+1][nums2.length+1];
for(int i = 1;i<=nums1.length;i++){
int a = nums1[i-1];
for(int j = 1;j<=nums2.length;j++){
int b = nums2[j-1];
if(a == b){
dp[i][j] = dp[i-1][j-1] +1;
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[nums1.length][nums2.length];
}
}
- 最大子序和
java
class Solution {
// public int maxSubArray(int[] nums) {
// int result = Integer.MIN_VALUE;
// int sum = 0;
// for(int i = 0;i<nums.length;i++){
// sum += nums[i];
// result = sum>result ? sum : result;
// if(sum < 0) sum = 0;
// }
// return result;
// }
public int maxSubArray(int[] nums) {
//确定dp数组(dp table)以及下标的含义
//dp[i]:包括下标i(以nums[i]为结尾)的最大连续子序列和为dp[i]
if(nums.length == 0){
return 0;
}
int[] dp = new int[nums.length+1];
int result = nums[0];
dp[0] = nums[0];
for(int i = 1;i<nums.length;i++){
dp[i] = Math.max(nums[i],dp[i-1] + nums[i]);
if(dp[i] > result){
result = dp[i];
}
}
return result;
}
}