欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 【Hot100】LeetCode—300. 最长递增子序列

【Hot100】LeetCode—300. 最长递增子序列

2024/10/25 6:19:57 来源:https://blog.csdn.net/weixin_44382896/article/details/142133427  浏览:    关键词:【Hot100】LeetCode—300. 最长递增子序列

目录

  • 1- 思路
    • 题目识别
    • 动规五部曲
  • 2- 实现
    • 最长递增子序列——题解思路
  • 3- ACM 实现


  • 原题链接:300. 最长递增子序列

1- 思路

题目识别

  • 识别1 :给出一个数组输入 nums
  • 识别2:严格递增的子序列,子序列可以是不连续的

动规五部曲

思路:

  • 1- 定义 dp 数组
    • dp[i] 代表长度为 i 的数组的最长递增子序列的长度
  • 2- 递推公式
    • if(nums[j] > nums[i]) 则更新 dp[j] = Math.max(dp[i] + 1,dp[j])

2- 实现

最长递增子序列——题解思路

在这里插入图片描述

class Solution {public int lengthOfLIS(int[] nums) {int len = nums.length;int[] dp = new int[len+1];// 2.递推公式// if(nums[i] > nums[j]) dp[j] = dp[i] + +1;// 初始化Arrays.fill(dp,1);for(int i = 1 ; i <= len;i++){for(int j = 1 ; j < i ; j++){if(nums[i-1] > nums[j-1]){dp[i] = Math.max(dp[j] + 1,dp[i]);}}}int res = 1;for(int i : dp){res = Math.max(i,res);}return res;}
}

3- ACM 实现

public class maxLenSub {public static int findMax(int[] nums){//1.定义 dpint len = nums.length;int[] dp = new int[len+1];// 2. 递推公式// if(nums[i] > nums[j])// 3.初始化Arrays.fill(dp,1);for(int i = 1 ; i <= len;i++){for(int j = 1 ; j < i ; j++){if(nums[i-1] > nums[j-1]){dp[i] = Math.max(dp[i],dp[j]+1);}}}int res = 1 ;for(int r:dp){res = Math.max(res,r);}return res;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);String input = sc.nextLine();input = input.replace("[","").replace("]","");String[] parts = input.split(",");int[] nums = new int[parts.length];for(int i = 0 ; i < nums.length;i++){nums[i] = Integer.parseInt(parts[i]);}System.out.println("结果是"+findMax(nums));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com