300. Longest Increasing Subsequence/DP

题目描述

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

For example,

Given [10, 9, 2, 5, 3, 7, 101, 18],

The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up: Could you improve it to O(n log n) time complexity?

LIS这道题目是典型的动规的题目,就是要找到一个序列的最长递增序列。

动规里面最有挑战就是找到状态转移方程。

代码实现

最简单的就是暴力破解:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        if(!len) return 0;
        vector<vector<int> > path(len, vector<int>(len, 0));
        int res = 0;

        // O(n^3)
        for(int k = 0; k < len; k++) {
            for(int i = k+1; i < len; i++) {
                for(int j = k; j < i; j++) {
                    if(nums[i] > nums[j]) {
                        path[k][i] = (path[k][j]+1 > path[k][i])?path[k][j]+1:path[k][i];
                        if(res < path[k][i]) res = path[k][i];
                    }    
                }
            }
        }
        return res+1;
    }
};

使用DP,这里只需要找到该序列的长度,所以可以写成:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        if(!len) return 0;
        vector<int> path(len, 0);
        int res = 0;

        for(int i = 1; i < len; i++) {
            for(int j = i-1; j >=0; j--) {
                if(nums[i] > nums[j]) {
                    path[i] = path[j] + 1 > path[i]? path[j]+1:path[i];
                    if(res < path[i]) res = path[i];
                }    
            }
        }
        return res+1;
    }
};

这里的状态方程可以参考【1】:以第k项结尾的LIS的长度是:保证第i项比第k项小的情况下,以第i项结尾的LIS长度加一的最大值,取遍i的所有值(i小于k)。

除了上面的一维状态方程以外,还可以写成二维的状态方程【1】。

这里写图片描述

找到最长递增序列的个数就是在每次符合条件给 Fi,k 赋值的时候对结果进行更新即可。

另外,对动规的理解可以看【2】。

参考链接:
【1】ILS状态方程:https://www.zhihu.com/question/23995189
【2】DP的精髓理解:https://www.zhihu.com/question/23995189/answer/35429905

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值