300. Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
- There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity. - Follow up: Could you improve it to O(n log n) time complexity?
Approach
- 这道题乍一看有点像Longest Increasing Sequence(最长不下降子序列),这道题确实也差不多是,只是变成了最长上升子序列,不过解法通用,我还是打算用动态规划思想解决。我们先来找找子问题,显然易见子问题就是, 当
i<j nums[i]<nums[j]
, 此时应该是要加一,即dp[j]=1+1
(dp代表最长上升子序列的长度),说明前面有一个数小于它,但是你不知道nums[i]
前面有没有小于它,如果有的话,就要一并加上并加上一,所以此时方程为dp[j]=dp[i]+1
,可是如果也有一个a<j && nums[a]<nums[j]
,所以这里我们就要取最优的结果dp[j]=max(dp[j],dp[i]+1) i<j
即状态转移方程,最后结果我们要遍历一遍dp
取大值,因为我们不知道哪里是最长上升子序列的尾。
Code
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0)return 0;
vector<int> dp(nums.size(), 1);
int maxn = 0;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[j] > nums[i]) {
dp[j] =max(dp[i] + 1,dp[j]);
}
}
maxn=max(maxn,dp[i]);
}
return maxn;
}
};