<LeetCode OJ> 300. Longest Increasing Subsequence

来源:互联网 发布:夜色钢琴淘宝 编辑:程序博客网 时间:2024/06/05 05:42

300. Longest Increasing Subsequence

My Submissions
Total Accepted: 11127 Total Submissions: 34521 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
 Dynamic Programming Binary Search


分析:

典型的动态规划问题

定义子问题:dp[i]表示第i个及其以前的元素的最大上升个数
显然第i个元素的最大上升序列是前面某个子问题的最大长度+1
当遍历到i时,重新将前面的遍历一遍,如果nums[i]>nums[j]并且dp[j]+1 > dp[i]
显然dp[i]就是dp[j]+1,遍历完0到j就是dp[i]就求出来了

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




第二种解法:

贪心策略+二分法

开辟一个栈,每次取“栈”(这里采用数组来实现)顶元素s和读到的元素a做比较,如果a>s,  则加入栈(将会有序);如果a<s,则二分查找栈中的比a大的第1个数,并替换。  最后序列长度为栈的长度。  我们替换之后最长序列长度没有改变,但序列Q的''潜力''增大,我们总是贪心的营造这种能产生最长长度的“潜力”,并且不影响其长度。  
举例:原序列为1,5,8,3,6,7  
栈为1,5,8,此时读到3,则用3替换5,得到栈中元素为1,3,8,  再读6,用6替换8,得到1,3,6,再读7,得到最终栈为1,3,6,7  ,最长递增子序列为长度4。 

参考自己以前的博文:

http://blog.csdn.net/ebowtang/article/details/45373557#t12


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50424074

原作者博客:http://blog.csdn.net/ebowtang

1 0