1143. 最长公共子序列
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
// 这个题和最长子数组不一样,这个不能暴力
// 这道题可以考虑dp,因为他的长度也就在1000以内
// dp[i][j] 表示在i-1为底 j -1为底的最长公共子序列
// 递推公式
// if text1[i-1] == text[j-1]
// dp[i][j] = dp[i-1][j-1] + 1
// acde
// acbe
// 如果是子数组的话,他的递推公式就是只考虑相等的情况,因为不等的话就是0 dp[i][j] = Math.max(dp[i-1][j-1] + 1,dp[i][j])
// abcde
// ace
// 如果是子序列的话,考虑两种情况
// 相等: dp[i][j] = dp[i-1][j-1] + 1
// 不等:例子:如果到abcd和ace的情况,一种就是abcd和ac,一种就是abc和ace比较
char[] text1_arr = text1.toCharArray();
char[] text2_arr = text2.toCharArray();
int res = 0;
int[][] dp = new int[text1_arr.length + 1][text2_arr.length + 1];
for(int i = 1;i <= text1_arr.length;i++){
for(int j = 1;j <= text2_arr.length;j++){
if(text1_arr[i-1] == text2_arr[j - 1]){
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_arr.length][text2_arr.length];
}
}
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++){
for(int j = 1;j <= nums2.length;j++){
if(nums1[i-1] == nums2[j-1]){
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];
}
}
暴力,超时
class Solution {
public int maxSubArray(int[] nums) {
// 暴力
int res = Integer.MIN_VALUE;
for(int i = 0;i < nums.length ;i++){
int count =0;
for(int j = i; j < nums.length;j++){
count += nums[j];
res = Math.max(count,res);
}
res = Math.max(count,res);
}
return res;
}
}
贪心太难想了,想不到
class Solution {
public int maxSubArray(int[] nums) {
// // 暴力
// int res = Integer.MIN_VALUE;
// for(int i = 0;i < nums.length ;i++){
// int count =0;
// for(int j = i; j < nums.length;j++){
// count += nums[j];
// res = Math.max(count,res);
// }
// res = Math.max(count,res);
// }
// return res;
// 贪心
int res =Integer.MIN_VALUE;
int count =0;
for(int i = 0;i < nums.length;i++){
count += nums[i];
if(res < count){
res = count;
}
if(count < 0) count = 0;
}
return res;
}
}
class Solution {
public int maxSubArray(int[] nums) {
// // 暴力
// int res = Integer.MIN_VALUE;
// for(int i = 0;i < nums.length ;i++){
// int count =0;
// for(int j = i; j < nums.length;j++){
// count += nums[j];
// res = Math.max(count,res);
// }
// res = Math.max(count,res);
// }
// return res;
// 贪心
// int res =Integer.MIN_VALUE;
// int count =0;
// for(int i = 0;i < nums.length;i++){
// count += nums[i];
// if(res < count){
// res = count;
// }
// if(count < 0) count = 0;
// }
// return res;
// dp数组
int [] dp = new int[nums.length + 1];
int res = Integer.MIN_VALUE;
for(int i = 0;i < nums.length;i++){
dp[i + 1] = Math.max(dp[i] + nums[i],nums[i]);
if(res < dp[i+1]){
res = dp[i+1];
}
}
return res;
}
}