【LeetCode】300. Longest Increasing Subsequence

300. Longest Increasing Subsequence

Description:
Given an unsorted array of integers, find the length of longest increasing subsequence.
Difficulty:Medium
Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 
方法1:暴力, 超时
  • Time complexity : O ( 2 n ) O\left ( 2^n \right ) O(2n)
  • Space complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
    思路:
    如果当前元素比前面元素prev大,有两种情况,用或者不用,用就+1
    反之,只有一种情况,不用
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        return helper(nums, INT_MIN, 0);
    }
    
    int helper(vector<int>& nums, int prev, int pos){
        if(pos == nums.size()) return 0;
        int use = 0;
        if(nums[pos] > prev)
            use = helper(nums, nums[pos], pos+1) + 1;
        int no_use = helper(nums, prev, pos+1);
        return max(use, no_use);
    }
};
方法2:动态规划
  • Time complexity : O ( n 2 ) O\left ( n^2 \right ) O(n2)
  • Space complexity : O ( n ) O\left ( n \right ) O(n)
    思路:
    dp[i] = max(dp[j])+1 if nums[i] > nums[j] ,( j = 0->i-1)
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        int res = 1;
        vector<int> dp(nums.size()+1);
        dp[0] = 1;
        for(int i = 1; i < nums.size(); i++){
            int max_val = 0;
            for(int j = 0; j < i; j++){
                if(nums[j] < nums[i]) max_val = max(dp[j], max_val);                
            }
            dp[i] = max_val + 1;
            res = max(dp[i], res);
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值