LLancelot / LeetCode

✍️ My LeetCode solutions, ideas and templates sharing. (我的LeetCode题解,思路以及各专题的解题模板分享。分专题归纳,见tag)
https://leetcode.com/lancelot_/
163 stars 40 forks source link

300. Longest Increasing Subsequence #14

Open LLancelot opened 4 years ago

LLancelot commented 4 years ago

题目 Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

二分查找 (nlogn)

动态规划 (n^2),不推荐

class Solution {
    public int lengthOfLIS(int[] arr) {
        int[] dp = new int[arr.length];
        Arrays.fill(dp, 1);
        int res = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int idx = 0; idx < i; idx++) {
                if (arr[idx] < arr[i]) {
                    dp[i] = Math.max(dp[i], dp[idx] + 1);
                }
            }
            res = Math.max(res, dp[i]);
        }
        return res;
    }
}