Leetcode 300. Longest Increasing Subsequence (Medium) (cpp)

Leetcode 300. Longest Increasing Subsequence (Medium) (cpp)

Tag: Dynamic Programming, Binary Search

Difficulty: Medium


/*

300. Longest Increasing Subsequence (Medium)

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?

*/
class Solution {
public:
    int lengthOfLIS(vector& nums) {
        int res = 0;
        int table[nums.size()];
        for (int i = 0; i < nums.size(); i++) {
            table[i] = 1;
            for (int j = 0; j < i; j++)
                if (nums[j] < nums[i]) table[i] = max(table[i], table[j] + 1);
            res = max(res, table[i]);
        }
        return res;
    }
};
class Solution {
public:
    int lengthOfLIS(vector& nums) {
        vector res;
        for(int i : nums) {
            auto it = lower_bound(res.begin(), res.end(), i);
            if (it == res.end()) res.push_back(i);
            else *it = i;
        }
        return res.size();
    }
};

Leetcode 300. Longest Increasing Subsequence (Medium) (cpp)_第1张图片Leetcode 300. Longest Increasing Subsequence (Medium) (cpp)_第2张图片

你可能感兴趣的:(Leetcode,C++,C++,Leetcode,Dynamic,Programming,Leetcode,Binary,Search,leetcode,cpp)