美文网首页
300. Longest Increasing Subseque

300. Longest Increasing Subseque

作者: 秦汉邮侠 | 来源:发表于2020-01-09 07:49 被阅读0次

    Problem:

    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?

    Idea:

    Dynamic Programming

    solution1

    // Author: Huahua
    // Running time: 29 ms
    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            if (nums.empty()) return 0;
            int n = nums.size();
            auto f = vector<int>(n, 1);
            for (int i = 1; i < n; ++i)
                for (int j = 0; j < i; ++j)
                    if (nums[i] > nums[j])
                        f[i] = max(f[i], f[j] + 1);
            return *max_element(f.begin(), f.end());
        }
    };
    

    solution2

    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            int n = nums.size();
            if (n == 0) return 0;        
            f_ = vector<int>(n, 0);        
            int ans = 0;
            for (int i = 0; i < n; ++i)
                ans = max(ans, LIS(nums, i));
            return ans;
        }
    private:
        vector<int> f_;
        // length of LIS ends with nums[r]
        int LIS(const vector<int>& nums, int r) {
            if (r == 0) return 1;
            if (f_[r] > 0) return f_[r];
            int ans = 1;
            for(int i = 0; i < r; ++i)
                if (nums[r] > nums[i])
                    ans = max(ans, LIS(nums, i) + 1);
            f_[r] = ans;
            return f_[r];
        }
    };
    

    solution3

    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            vector<int> dp(nums.size(), 1);
            int res = 0;
            for (int i = 0; i < nums.size(); ++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;
        }
    };
    

    代码来源

    https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-300-longest-increasing-subsequence/

    相关文章

      网友评论

          本文标题:300. Longest Increasing Subseque

          本文链接:https://www.haomeiwen.com/subject/gageactx.html