LC.P300[最长递增子序列]

方法一:记忆化搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int[] nums, cache;

public int lengthOfLIS(int[] nums) {
this.nums = nums;
int n = nums.length;
cache = new int[n];
int ans = 0;
for (int i = 0; i < n; ++i) {
ans = Math.max(ans, dfs(i));
}
return ans;
}

private int dfs(int i) {
if (cache[i] > 0) return cache[i];
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) cache[i] = Math.max(cache[i], dfs(j));
}
return ++cache[i];
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$

方法二:1:1翻译成递推

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int lengthOfLIS(int[] nums) {
int n = nums.length, ans = 0;
int[] f = new int[n];
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) f[i] = Math.max(f[i], f[j]);
}
ans = Math.max(ans, ++f[i]);
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$