LeetCode 300. 最长递增子序列
题目描述
考察公司:滴滴
思路分析
dp[i]
表示以nums[i]
结尾的最长递增子序列的长度
参考代码
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)
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;
}
}
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用