LeetCode 题解(Week6):300. Longest Increasing Subsequence

原题目

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.

Follow up: Could you improve it to O(n log n) time complexity?

中文大意

给定一个序列,找到其最长的递增子序列长度,如[10, 9, 2, 5, 3, 7, 101, 18],它的最长的递增子序列为[2, 3, 7, 101],因此答案为4

题解

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

        for(int i = 1; i< nums.size();i++)
        {
            int currlen =1 ;

            for(int j = 0; j < i ; j++)
            {
                if(nums[j]<nums[i] && currlen < v[j]+1)
                    currlen = v[j]+1;
            }
            v[i] = currlen;
        }

        int res = 0;
        for(int i =0 ;i < v.size();i++)
        {
            if(res < v[i])
                res = v[i];
        }
        return res;
    }
};

解题思路

这道题是经典的动态规划问题,每一次迭代都依赖于之前的结果。开辟计数器数组v,元素都初始化为1,v[i]代表以i为结尾的子串,其递增子序列的最长长度,v的计算过程如下:

  1. 初始化:v[0] = 1 ,以nums[0]为结尾的子串,自然只有v[0]一个
  2. 迭代求v[i]:
    • j = 0 : i-1
    • 判断num[j]是否小于num[i](若小于,意味着num[i]可以接到num[j]的后面,形成新的递增子序列)
    • 若num[j] < num[i],v[j]+1则成为v[i]的一个候选值
    • 取上述候选值中最大的一个,作为v[i]的值

举例说明(以[10, 9, 2, 5, 3, 7, 101, 18]为例):
pass0:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 1, 1, 1, 1, 1]

pass1:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 1, 1, 1, 1, 1](9不能接到10的后面,因此最长子序列就是它本身)

pass2:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 1, 1, 1, 1, 1](同上)

pass3:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 2, 1, 1, 1, 1] (接到2的后面,得到最长子序列(2,5))

pass4:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 2, 2, 1, 1, 1] (接到2的后面,得到最长子序列(2,3))

pass5:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 2, 2, 3, 1, 1] (接到3的后面,得到最长子序列(2,3,7))

pass6:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 2, 2, 3, 4, 1] (接到7的后面,得到最长子序列(2,3,7,101))

pass7:
nums:[10, 9, 2, 5, 3, 7, 101, 18]
ctr: [1, 1, 1, 2, 2, 3, 4, 4] (接到7的后面,得到最长子序列(2,3,7,18))

最终,序列[10, 9, 2, 5, 3, 7, 101, 18]的最长递增子序列的长度为4

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值