力扣:300.最长上升子序列(LIS)
1、 题目
给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。
示例 1:
输入:nums = [10,9,2,5,3,7,101,18]
输出:4
解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
示例 2:输入:nums = [0,1,0,3,2,3]
输出:4
示例 3:输入:nums = [7,7,7,7,7,7,7]
输出:1提示:
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence
2、 解答
定义dp数组:
-
数组大小与nums数组大小一致
-
dp[i] 表示 以nums[i] 结尾的子序列最大长度;
-
初始化为dp数组都为1(以nums[i]结尾的子序列最小长度为它本身)
遍历每一个nums中的元素:
从头遍历到nums[i],找到比nums[i]小的nums[j],dp[i] = max(dp[i],dp[j] + 1);
最后返回dp数组中的最大值。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> dp(nums.size(), 1);
for(int i = 0; i < nums.size(); i++){
for(int j = 0; j < i; j++){
if(nums[i] > nums[j]){
dp[i] = max(dp[j] + 1, dp[i]);
}
}
}
int res = 0;
for(auto i : dp){
res = max(res,i);
}
return res;
}
};