Leetcode300. Longest Increasing Subsequence

Leetcode300. Longest Increasing Subsequence

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. 

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O ( n 2 ) O(n^2) O(n2) complexity.
    Follow up: Could you improve it to O(n log n) time complexity?
动态规划

注意子串与子序列的区别:

  • 子序列(subsequence):并不要求在原序列中连续
  • 子串(substring、subarray):在原序列中一定是连续的

第一步:定义状态

dp[i] 表示以 nums[i] 结尾的“最长上升子序列”的长度

第二步:状态转移方程

dp[i] 等于索引 i 之前严格小于 nums[i] 的状态最大者 + 1 + 1 +1

d p [ i ] = M A X 0 ⩽ j < i , n u m s [ j ] < n u m s [ i ] d p [ j ] + 1 dp[i]=\mathop{\mathbb{MAX}}\limits_{0\leqslant j< i, nums[j]<nums[i]} dp[j]+1 dp[i]=0j<i,nums[j]<nums[i]MAXdp[j]+1

第三步:考虑初始化

dp[0] = 1,1个字符当然也是长度为 1 的上升子序列。

第四步:考虑输出

所有dp[i]的最大值: M A X 1 ⩽ i ⩽ n d p [ i ] \mathop{\mathbb{MAX}}\limits_{1\leqslant i \leqslant n} dp[i] 1inMAXdp[i]

第五步:考虑状态压缩

无法状态压缩,因为要用到之前的所有d[i]

  • 时间复杂度: O ( N 2 ) O(N^2) O(N2)
  • 空间复杂度: O ( N ) O(N) O(N)
import java.util.Arrays;
public class Solution {
    public int lengthOfLIS(int[] nums) {
        int len = nums.length;
        if (len < 2) {
            return len;
        }

        int[] dp = new int[len];
        Arrays.fill(dp, 1);
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }

        int res = 0;
        for (int i = 0; i < len; i++) {
            res = Math.max(res, dp[i]);
        }
        return res;
    }
}
动态规划:使用贪心和二分来优化时间复杂度

看不明白

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值