[leetcode]300. Longest Increasing Subsequence

[leetcode]300. Longest Increasing Subsequence


Analysis

raining outside…—— [每天刷题并不难0.0]

Given an unsorted array of integers, find the length of longest increasing subsequence.
[leetcode]300. Longest Increasing Subsequence_第1张图片

Explanation:

Inspired by http://www.cnblogs.com/grandyang/p/4938187.html

Implement

Dynamic Programing:

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

Binary Research:

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len = nums.size();
        vector<int> dp;
        for(int i=0; i<len; i++){
            int left = 0;
            int right = dp.size();
            while(left<right){
                int mid = left+(right-left)/2;
                if(dp[mid]<nums[i])
                    left = mid+1;
                else
                    right = mid;
            }
            if(right >= dp.size())
                dp.push_back(nums[i]);
            else
                dp[right] = nums[i];
        }
        return dp.size();
    }
};

你可能感兴趣的:(LeetCode,Medium,DP,Binary,Search,leetcode)