Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 300. Longest Increasing Subsequence

Rain Hu

300. Longest Increasing Subsequence


一、題目

Given an integer array nums, return the length of the longest strictly increasing subsequence

Example 1:

Example 2:

Example 3:

Constraints:

Follow up: Can you come up with an algorithm that runs in O(n log n) time complexity


二、分析

三、解題

1. DP

int lengthOfLIS(vector<int>& nums) {
    int n = nums.size();
    vector<int> dp(n, 1);
    int res = 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], dp[j] + 1);
                res = max(res, dp[i]);
            }
        }
    }
    return res;
}
int lengthOfLIS(vector<int>& nums) {
    int n = nums.size();
    vector<int> dp(n, INT_MAX);     // dp[n] 裝的是實際排出來的數字,沒排到的位置以 INT_MAX 填滿,以使用 binary search
    int res = 0;
    for (int i = 0; i < n; i++) {
        auto it = lower_bound(dp.begin(), dp.end(), nums[i]);
        *it = min(*it, nums[i]);    // 用 greedy 的想法,同樣位子上,數字愈小,愈有可能形成最長遞增子序列
        res = max(res, (int)(it - dp.begin())+1);
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1143. Longest Common Subsequence
Next
[LeetCode] 2468. Split Message Based on Limit