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]最长的的递增子串的长度。

LeetCode300. Longest Increasing Subsequence

工程代码下载

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;
    }
};

相关文章:

  • 2022-03-04
  • 2022-03-05
  • 2021-08-18
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2021-11-09
  • 2021-07-29
  • 2021-12-28
相关资源
相似解决方案