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?

Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.

这个状态转移方程还是容易想的,定义dp[i]是在第i个位置能取得的最大长度,那么dp[i]=max(dp[i],dp[j]+1),其中j∈[0,i),加1的前提是dp[j]<dp[i],但是!一定不要粗心,最后的答案应该是dp数组中最大的那个,所以如果不怕浪费时间,可以最后sort一下再return dp[n-1],否则的话可以弄一个int型的变量res每次和得到的dp[i]比一比,总是取最大的res,最后return res

AC代码:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int n=nums.size();
        vector<int>dp(n,0);
        if(n==0)return 0;
        for(int i=0;i<n;i++){
            dp[i]=1;
            for(int j=0;j<i;j++){
                if(nums[j]<nums[i])
                    dp[i]=max(dp[i],dp[j]+1);
            }
        }
        sort(dp.begin(),dp.end());
        return dp[n-1];
    }
};

LeetCode的测试样例只有24个,如果直接return dp[n-1]只有两个样例通不过,哈哈哈哈。。。。(虽然这好像也不是什么好笑的事。。。)

进一步地,解决这个问题的算法可以被优化到O(nlogn),详细的介绍可以看这里:http:www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值