leetcode 300

原题链接

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

讨论区的人才有更好的解决方案,利用 STL 的 lower_bound 函数,效率提升不少。

class Solution{
public:
    int lengthOfLIS(vector<int>& nums) {
    vector<int> ans;
    for (int a : nums)
        if (ans.size() == 0 || a > ans.back()) ans.push_back(a);
        else *lower_bound(ans.begin(), ans.end(), a) = a;
    return ans.size();
}    
};

猜你喜欢

转载自www.cnblogs.com/walnuttree/p/10626590.html