300. Longest Increasing Subsequence最长递增子序列

来源:互联网 发布:医院感染管理三级网络 编辑:程序博客网 时间:2024/06/06 18:21

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?

【思路】动态规划:dp[i]表示 s.substr(0,i)中的最长递增子序列。初始dp[i] = 1, 检查i-1之前的,如有nums[j] < nums[i]的,dp[i]则更新为 dp[i] 与dp[j]+1之间最大的。

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



0 0