zoukankan      html  css  js  c++  java
  • leetcode@ [300] Longest Increasing Subsequence (记忆化搜索)

    https://leetcode.com/problems/longest-increasing-subsequence/

    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 dfs(vector<int>& nums, vector<int> &dp, int v) {
            if(dp[v]) return dp[v];
            if(v == 0) return 0;
            
            int res = -1;
            for(int nv=v-1;nv>=0;--nv) {
                if(nums[nv] >= nums[v]) continue;
                res = max(res, dfs(nums, dp, nv));
            }
            dp[v] = res + 1;
            return dp[v];
        }
        int lengthOfLIS(vector<int>& nums) {
            if(nums.size() == 0 || nums.size() == 1) return nums.size();
            
            vector<int> dp(nums.size(), 0);
            
            int res = -1;
            for(int i=nums.size()-1;i>=0;--i) {
                dp[i] = dfs(nums, dp, i);
                res = max(res, dp[i] + 1);
            }
            
            return res;
        }
    };
    View Code
  • 相关阅读:
    Go语言并发编程
    Go语言package
    大数据实践(十) Spark多种开发语言、与Hive集成
    大数据实践(九)--sqoop安装及基本操作
    Go语言错误处理
    Go语言接口
    Go语言面向对象
    数据库基础了解
    PL/SQL语句快捷输入设置
    重载操作符介绍
  • 原文地址:https://www.cnblogs.com/fu11211129/p/4962032.html
Copyright © 2011-2022 走看看