版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/89047308
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(n^2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
题目:最长递增子序列的长度。
思路:同LeeCode673. Number of Longest Increasing Subsequence。用dp[i]
表示对于子串nums[0...i]
最长的的递增子串的长度。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
if(n <= 0) return 0;
vector<int> dp(n, 1);
int max_len = 1;
for(int i = 0; i < n; ++i){
for(int j = 0; j < i; ++j){
if(nums[j] < nums[i])
dp[i] = max(dp[i], dp[j] + 1);
}
max_len = max(max_len, dp[i]);
}
return max_len;
}
};