300. Longest Increasing Subsequence(DP经典问题)

来源:互联网 发布:相宜本草淘宝有假货吗 编辑:程序博客网 时间:2024/06/04 20:47

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/



原创粉丝点击