LeetCode 300. 最长递增子序列

题目描述

300. 最长递增子序列

考察公司:滴滴

image-20230306132026731

思路分析

dp[i] 表示以 nums[i] 结尾的最长递增子序列的长度

image-20250510003516193

image-20250510084018577

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func lengthOfLIS(nums []int) int {
	// dp[i] 表示以 nums[i] 结尾的最长递增子序列长度
	dp := make([]int, len(nums))

	res := 1
	for i := 0; i < len(nums); i++ {
		dp[i] = 1
		for j := 0; j < i; j++ {
			// 如果当前 nums[i] 可以接在 nums[j] 后面
			if nums[j] < nums[i] {
				dp[i] = max(dp[i], dp[j]+1)
			}
		}
		// 更新全局最大长度
		res = max(res, dp[i])
	}

	return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func lengthOfLIS(nums []int) int {
	dp := make([]int, len(nums))
	res := 1
	for i := 0; i < len(nums); i++ {
		dp[i] = 1
		for 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
}
  • 时间复杂度:O(n²)
  • 空间复杂度:O(n)

➡️ 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
    public int lengthOfLIS(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        int res = 0;
        for (int i = 0; i < n; i++) {
            dp[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            res = Math.max(res, dp[i]);
        }
        return res;
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/87131039
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!