[leetcode] 300. Longest Increasing Subsequence (Medium)

Posted Ruoh3kou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 300. Longest Increasing Subsequence (Medium)相关的知识,希望对你有一定的参考价值。

题意:

求最长增长的子序列的长度。

思路:

利用DP存取以i作为最大点的子序列长度。

Runtime: 20 ms, faster than 35.21% of C++ online submissions for Longest Increasing Subsequence.

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

      for (int j = 0; j < i; j++)
      {
        if (nums[i] > nums[j])
          curmaxNum = max(dp[j], curmaxNum);
      }
      dp[i] = curmaxNum + 1;
      resNum = max(dp[i], resNum);
    }
    return resNum;
  }
};

解法二:

讨论区里的最优解:

利用一个容器去动态存储一个增长子序列,遍历Nums,对每一个nums[i],在容器中寻找是否有大于等于nums[i]的元素,若存在,则将改值替换为nums[i];

若不存在,则将nums[i]加入该容器,于是容器中的元素永远是 小于 关系的。

0ms.

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> res;
        for(int i=0; i<nums.size(); i++) {
            auto it = std::lower_bound(res.begin(), res.end(), nums[i]);
            if(it==res.end()) res.push_back(nums[i]);
            else *it = nums[i];
        }
        return res.size();
    }
};

 

以上是关于[leetcode] 300. Longest Increasing Subsequence (Medium)的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 300. Longest Increasing Subsequence (Medium)

Leetcode 300. Longest Increasing Subsequence

LeetCode 1027. Longest Arithmetic Sequence

Leetcode 300 Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence

LeetCode 300. Longest Increasing Subsequence