300.最长上升子序列

给定一个无序的整数数组,找到其中最长上升子序列的长度。

示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:

可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。

思路:

  • 运用动态规划,当第 i个元素时,用这个元素,去与前面的 i-1个元素比较;
  • 当 nums[i] > nums[j] 时, dp[i] = dp[j] + 1; 取 dp[j] 的最大值,写入dp[i];
  • 用一个变量 res 记录最大的结果个数。

class Solution {
    public int lengthOfLIS(int[] nums) {
        if(nums.length == 0) return 0;
        int res = 0;
        int[] dp = new int[nums.length];
        for(int i = 0; i < nums.length; 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://www.cnblogs.com/luo-c/p/13899061.html