【陪伴式刷题】Day 46|动态规划|300.最长递增子序列(Longest increasing Subsequence)

68 阅读1分钟

(刷题顺序以及题解参考卡哥的代码随想录)

题目描述

英文版描述

Given an integer array nums, return the length of the longest strictly increasing

subsequence

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [0,1,0,3,2,3] Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7] Output: 1

Constraints:

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

英文版地址

leetcode.com/problems/lo…

中文版描述

给你一个整数数组 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

提示:

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

中文版地址

leetcode.cn/problems/lo…

解题方法

class Solution {
    public int lengthOfLIS(int[] nums) {
        // dp[i] 表示以nums[i]为结尾的最长子序列的长度
        int[] dp = new int[nums.length];
        // 初始化
        dp[0] = 1;
        int result = 1;
        for (int i = 1; i < nums.length; i++) {
            for (int j = i; j >= 0; j--) {
                if (nums[i] > nums[j]) {
                    dp[i] = Math.max(dp[i], dp[j]);
                }
            }
            dp[i] = dp[i] + 1;
            result = Math.max(result, dp[i]);
        }
        return result;
    }
}

复杂度分析

  • 时间复杂度:O(n*2),其中 n 是数组元素数
  • 空间复杂度:O(n)