LeetCode 300. Longest Increasing Subsequence C++

300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

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. 

Note:

  • 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?

Approach

  1. 这道题乍一看有点像Longest Increasing Sequence(最长不下降子序列),这道题确实也差不多是,只是变成了最长上升子序列,不过解法通用,我还是打算用动态规划思想解决。我们先来找找子问题,显然易见子问题就是, 当 i<j nums[i]<nums[j], 此时应该是要加一,即dp[j]=1+1(dp代表最长上升子序列的长度),说明前面有一个数小于它,但是你不知道nums[i] 前面有没有小于它,如果有的话,就要一并加上并加上一,所以此时方程为dp[j]=dp[i]+1,可是如果也有一个a<j && nums[a]<nums[j],所以这里我们就要取最优的结果dp[j]=max(dp[j],dp[i]+1) i<j即状态转移方程,最后结果我们要遍历一遍dp取大值,因为我们不知道哪里是最长上升子序列的尾。

Code

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

            }
             maxn=max(maxn,dp[i]);
        }
        return maxn;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值