300. Longest Increasing Subsequence

Description:

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.


简要题解:

采用动态规划。

子问题c(i)为从序列的第0个元素开始,到第i个元素的子序列。

每个子问题c(i)维护两个值: 当前最长递增子序列的长度(记为first); 包含元素i的最长递增序列的长度(记为second)。

第一个子问题的这两个值分别为: 1, 1。

c(i)与c(i-1)的关系是: 如果元素i大于元素i-1,则c(i).first = c(i-1).first + 1, c(i).second = c(i-1).second + 1;否则,c(i).second = max(c(j).second + 1),其中0 <= j < i且元素j小于元素i,没有这样的元素j时,c(i).second = 1,同时,c(i).first = max(c(i).second, c(i-1).first)。


代码:

#include<utility>

using namespace std;

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.size() == 0)
            return 0;

        vector<pair<int, int> > LIS(nums.size());

        LIS[0].first = 1;
        LIS[0].second = 1;
        for (int i = 1; i < LIS.size(); i++) {
            LIS[i].second = 1;
            for (int j = i - 1; j >= 0; j--)
                if (nums[i] > nums[j])
                    LIS[i].second = (LIS[j].second + 1 > LIS[i].second) ? LIS[j].second + 1 : LIS[i].second;
            
            LIS[i].first = (LIS[i].second > LIS[i-1].first) ? LIS[i].second : LIS[i-1].first;
        }

        return LIS[LIS.size()-1].first;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值