给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
输入:nums = [10,9,2,5,3,7,101,18] 输出:4 解释:最长递增子序列是 [2,3,7,101],因此长度为 4
输入:nums = [0,1,0,3,2,3] 输出:4
题意解析:最长递增子序列= 给定无序找出最长递增子序列长度
思路分析:利用动态规划的思想,减小问题规模
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 | 1 | 1 | 1 | 1 |
实际上我还是没有根本的掌握这种思想,只能应用其流程,如上表所示,整个流程就是,遍历数组,
当前位置与之前的都比较,如果大于之前的值,就找到最其中的最大值+1作为该当前位置的下标
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 |
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 |
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 |
因为5大于2 所以 max = 1+1 =2;
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 | 2 |
同理 3大于2 max = 1+1=2
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 | 2 | 2 |
同理 7大于 2 5 3 max = 2+1 =3
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 | 2 | 2 | 3 |
同理 101 大于所有 max = 3+1 =4
10 | 9 | 2 | 5 | 3 | 7 | 101 |
1 | 1 | 1 | 2 | 2 | 3 | 4 |
代码实现:
class Solution {
public int lengthOfLIS(int[] nums) {
int [] dp = new int[nums.length];
dp[0]=1;
int maxans =1;
for(int i =1;i< nums.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
dp[i] =Math.max(dp[i], dp[j] + 1);
}
}
result = Math.max(maxans, dp[i]);
}
return result;
}
}