zoukankan      html  css  js  c++  java
  • 300. Longest Increasing Subsequence

    原题链接

    300. Longest Increasing Subsequence

    题目描述

    给你一个整数数组 nums ,找到其中最长严格递增子序列的长度。
    子序列是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7] 是数组 [0,3,1,6,2,2,7] 的子序列。

    示例 1:
    输入:nums = [10,9,2,5,3,7,101,18]
    输出:4
    解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。

    示例 2:
    输入:nums = [0,1,0,3,2,3]
    输出:4

    示例 3:
    输入:nums = [7,7,7,7,7,7,7]
    输出:1

    问题分析

    这题用dp进行解决

    dp[i]定义为nums数组中 nums[0, ..., i] 这个子数组 的最长上升子序列的长度

    那么dp[i] = max(dp[j]) + 1, 其中 0 <= j < i 且 nums[j] < nums[i]

    最后,整个数组的最长上升子序列即所有dp[i]中的最大值。

    LISlength = max(dp[i]) 0 <= i < n

    代码

    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            int n = nums.size();
            vector<int> dp(n, 1);
            dp[0] = 1;
    
            int res = 1;
            for(int i = 1; i < n; i++){
                for(int j = 0; j < i; j++){
                    if(nums[j] < nums[i]) dp[i] = max(dp[i], dp[j]+1);
                }
    
                res = max(res, dp[i]);
            }
    
            return res;
        }
    };
    
    只有0和1的世界是简单的
  • 相关阅读:
    Exchanger
    信号量Semaphore
    CountDownLatch
    Condition
    WCF接口实例介绍
    时间显示
    pymysql-execute
    python之迭代器与生成器
    python之装饰器
    python之函数
  • 原文地址:https://www.cnblogs.com/nullxjx/p/15022883.html
Copyright © 2011-2022 走看看