dp二分

【leetcode】300. Longest Increasin

2019-05-13  本文已影响0人  邓泽军_3679

1、题目描述

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:

Follow up: Could you improve it to O(n log n) time complexity?

2、问题描述:

3、问题关键:

状态表示:f[i]表示以第i个元素结尾的最长的子序列。
状态转移:f[i] = max(f[i], f[j] + 1),如果第j个元素比 第i个元素小的话。

长度为i的最小元素,一定比长度为i+1的结束的元素 小。可以通过更新长度为i个元素的结束的最小值,就可以得到最长的子序列。

4、C++代码:

算法1:DP
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n, 0);
        for (int i = 0; i < n; i ++) {
            f[i] = 1;
            for (int j = 0; j < i; j ++) 
                if (nums[j] < nums[i]) 
                    f[i] = max(f[i], f[j] + 1);
        }
        int res = 0;
        for (int i = 0; i < n; i ++) res = max(res, f[i]);
        return res;
        
    }
};
算法2:(二分)
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int n = nums.size();
        vector<int> q(n);
        int t = 0;
        for (auto x : nums) {
            if (!t || x > q[t - 1]) q[t ++] = x;
            else {
                int l = 0, r = t - 1;
                while(l < r) {
                    int mid = l + r >> 1;
                    if (q[mid] >= x) r = mid;
                    else l = mid + 1;
                }
                q[r] = x;
            }
        }
        return t;
    }
};

上一篇下一篇

猜你喜欢

热点阅读