LeetCode 300 Longest Increasing Subsequence
Given an integer array nums
, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7]
is a subsequence of the array [0,3,1,6,2,2,7]
.
Solution
我们用 \(dp[i]\) 表示以 \(i\) 结尾的最长长度。考虑转移:
\[dp[i]=\max(dp[i],dp[j]+1)
\]
其中 \(j<i\),且:
\[nums[i]>nums[j]
\]
此时我们需要遍历所有的 \(j<i\), 所以复杂度为 \(O(n^2)\)
点击查看代码
class Solution {
private:
int dp[2502];
int ans = 1;
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n==1)return 1;
for(int i=0;i<n;i++)dp[i]=1;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j])dp[i]=max(dp[i],1+dp[j]);
}
ans = max(ans, dp[i]);
}
return ans;
}
};