Day46 算法记录| 动态规划 13(子序列)

300.最长递增子序列

视频解析:

第一层for循环遍历每一个元素,
------- 第二层for循环找到当前元素前面有几个小于该值的元素
结尾需要统计最多的个数

class Solution {
    public int lengthOfLIS(int[] nums) {
    int n = nums.length;
    int[] dp = new int[n];
    //1.初始化
    Arrays.fill(dp,1);
    int res =1;
    for(int i=1;i<n;i++){
        for(int j=0;j<i;j++){
            if(nums[j]<nums[i]){
               dp[i] = Math.max(dp[i],dp[j]+1);
            }
        }
     res = Math.max(res,dp[i]);
    }

    return res;
    }
}

674. 最长连续递增序列

方法一:动态规划:dp[i]表示前面有几个连续小于当前位置的值

class Solution {
    public int findLengthOfLCIS(int[] nums) {
    
    int n = nums.length;
    int[] dp = new int[n];
    Arrays.fill(dp,1);
    int res =1;

    for(int i=1;i<n;i++){
      if(nums[i-1]<nums[i]){
          dp[i] = dp[i-1]+1;
      }
      
      res = Math.max(res,dp[i]);
    }
    return res;
    }
}

方法二:贪心

class Solution {
    public int findLengthOfLCIS(int[] nums) {
      int n = nums.length;
    int count =1;
    int res =1;

    for(int i=0;i<n-1;i++){
      if(nums[i]<nums[i+1]){
        count++;
      }else{
        count=1;
      }
       res = Math.max(res,count);
    }
     return res;
    }
}

718. 最长重复子数组

在这里插入图片描述

讲解的很好

class Solution {
    public int findLength(int[] A, int[] B) {
    int res =0;

    int[][] dp = new int[A.length+1][B.length+1];
    for(int i=1;i<=A.length;i++){
        for(int j =1;j<=B.length;j++){
            if(A[i-1] == B[j-1]){
                dp[i][j] = dp[i-1][j-1]+1;
            }
            res =Math.max(dp[i][j],res);
        }
    }
 return res;
    }
}

方法二:一维数组
因为当前元素依赖于(x-1,y-1),所以就需要从后向前去遍历
相当于在二维空间里面,从最后一行开始遍历

class Solution {
    public int findLength(int[] A, int[] B) {
    int res =0;
    int[] dp = new int[B.length+1];

    for(int i=1;i<=A.length;i++){ // 就像是商品
        for(int j =B.length;j>0;j--){
           if(A[i-1]==B[j-1]){
               dp[j] = dp[j-1]+1;
           }else{
               dp[j] =0;
           }
            res = Math.max(res,dp[j]);
        }
    }
 return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值