300. 最长递增子序列
动态规划
import java.util.Arrays;
class Solution {
public int lengthOfLIS(int[] nums) {
/**
* dp[i]定义为以nums[i]结尾的最长递增子序列
* 每个数字自己都可以构成一个序列,因此初始化长度都为1
*/
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int max = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]){
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
/**
* 因为这个序列必须要以nums[i]结尾,所以以nums[nums.length - 1]结尾的子序列长度dp[nums.length - 1]不一定是最大值
*/
max = Math.max(max, dp[i]);
}
return max;
}
}
/**
* 时间复杂度 O(n^2)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/longest-increasing-subsequence/