给定长度为N的数组,返回最长自增子序列的长度
Example:
Input: [10,9,2,5,3,7,101,18]
Ouput: 4
Explanation: 最长自增子序列是[2,3,7,101],长度为4
Input: [10,9,2,5,3,7,101,18,19]
Ouput: 4
Explanation: 最长自增子序列是[2,3,7,18,19],长度为5
public class Solution {
public int lengthOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = ;
int[] dp = new int[n];
int max = 1;
for (int i = 0; i < nums.length; i++) {
dp[i] = 1; // 初始化dp[i],因为每个元素自身至少可以构成一个长度为1的递增子序列
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
max = Math.max(max, dp[i]); // 更新最长递增子序列的长度
}
return max;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
System.out.println("Length of Longest Increasing Subsequence is " + solution.lengthOfLIS(nums));
}
}