赞
踩
题目:300. 最长递增子序列 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
- public class Solution {
- public int LengthOfLIS(int[] nums) {
- int result = 1;
- int n = nums.Length;
- int[] dp = new int[n];
- Array.Fill(dp, 1);
-
- for(int i = 1; i < n; i ++)
- {
- for(int j = 0; j < i; j ++)
- {
- if(nums[i] > nums[j]) dp[i] = Math.Max(dp[i], dp[j] + 1);
- }
- result = dp[i] > result ? dp[i] : result;
- }
- foreach(int num in dp)
- {
- Console.WriteLine(num);
- }
- return result;
- }
- }
注意:
1、数组元素要初始化为1
2、返回值不是dp[i],是dp数组中的最大值
题目:674. 最长连续递增序列 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
上题的变体,与nums[i]前每一个连续的元素比较变为前一个元素比较
- public class Solution {
- public int FindLengthOfLCIS(int[] nums) {
- int n = nums.Length;
- int[] dp = new int[n];
- Array.Fill(dp, 1);
- int result = 1;
-
- for(int i = 1; i < n; i ++)
- {
- if(nums[i] > nums[i-1]) dp[i] = dp[i-1] + 1;
- result = Math.Max(result, dp[i]);
- }
-
- return result;
- }
- }
题目:718. 最长重复子数组 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
- public class Solution {
- public int FindLength(int[] nums1, int[] nums2) {
- int n = nums1.Length;
- int m = nums2.Length;
- int[,] dp = new int[n,m];
- int result = 0;
-
- for(int i = 0; i < n; i ++)
- {
- for(int j = 0; j < m; j ++)
- {
- if(i == 0 || j == 0) dp[i,j] = nums1[i] == nums2[j] ? 1 : 0;
- else dp[i,j] = nums1[i] == nums2[j] ? dp[i-1, j-1] + 1: 0;
- result = Math.Max(result, dp[i,j]);
- }
- }
- return result;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。