LeetCode 300.最长递增子序列
题目链接:https://leetcode.cn/problems/longest-increasing-subsequence/description/
文章链接:https://programmercarl.com/0300.%E6%9C%80%E9%95%BF%E4%B8%8A%E5%8D%87%E5%AD%90%E5%BA%8F%E5%88%97.html
思路
* dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度* 位置i的最长升序子序列等于j从0到i-1各个位置的最长升序子序列 + 1 的最大值。* 所以:if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
public static int lengthOfLIS(int[] nums) {int[] dp = new int[nums.length];int res = 1;Arrays.fill(dp, 1);for (int i = 1; i < nums.length; i++) {// 位置i的最长升序子序列等于j从0到i-1各个位置的最长升序子序列 + 1 的最大值。for (int j = 0; j <= i - 1; j++) {if (nums[i] > nums[j])dp[i] = Math.max(dp[i],dp[j] + 1);}res = Math.max(res, dp[i]);}return res;}
LeetCode 674. 最长连续递增序列
题目链接:https://leetcode.cn/problems/longest-continuous-increasing-subsequence/description/
文章链接:https://programmercarl.com/0674.%E6%9C%80%E9%95%BF%E8%BF%9E%E7%BB%AD%E9%80%92%E5%A2%9E%E5%BA%8F%E5%88%97.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
思路
* dp[i]表示i之前包括i的以nums[i]结尾的最长递增子序列的长度,不一定以下标0为起始* 因为本题要求是连续递增子序列,所以只需要和前一个元素比较即可,不用遍历之前所有元素
public int findLengthOfLCIS(int[] nums) {int[] dp = new int[nums.length];Arrays.fill(dp, 1);int res = 1;for (int i = 1; i < nums.length; i++) {if (nums[i] > nums[i - 1])dp[i] = dp[i - 1] + 1;res = Math.max(res, dp[i]);}return res;}
LeetCode 718. 最长重复子数组
题目链接:https://leetcode.cn/problems/maximum-length-of-repeated-subarray/description/
文章链接:https://programmercarl.com/0718.%E6%9C%80%E9%95%BF%E9%87%8D%E5%A4%8D%E5%AD%90%E6%95%B0%E7%BB%84.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
思路
* dp[i][j] :以下标i - 1为结尾的A,和以下标j - 1为结尾的B,最长重复子数组长度为dp[i][j]。* (特别注意: “以下标i - 1为结尾的A” 标明一定是 以A[i-1]为结尾的字符串 )* 根据dp[i][j]的定义,dp[i][j]的状态只能由dp[i - 1][j - 1]推导出来。* 即当A[i - 1] 和B[j - 1]相等的时候,dp[i][j] = dp[i - 1][j - 1] + 1;
public int findLength(int[] nums1, int[] nums2) {int res = 0;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;res = Math.max(res, dp[i][j]);}}}return res;}