300. **Longest Increasing Subsequence (最长递增子序列)

​https://leetcode.com/problems/longest-increasing-subsequence/description/​

题目描述

Given an integer array ​​nums​​, return the length of the longest strictly increasing subsequence.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, ​​[3,6,2,7]​​​ is a subsequence of the array ​​[0,3,1,6,2,2,7]​​.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

Constraints:

  • ​1 <= nums.length <= 2500​
  • ​-10^4 <= nums[i] <= 10^4​

Follow up:

  • Could you come up with the​​O(n^2)​​ solution?
  • Could you improve it to​​O(n log(n))​​ time complexity?

代码实现

给定一个未排序的整数数组, 将其中最长递增子序列的长度求出来. 这道最长递增子序列印象很深刻~ 首先考虑使用动态规划来进行求解. 定义 ​​dp[i]​​​ 表示以 ​​nums[i]​​​ 结尾的数组中最长递增子序列的长度. 注意这个定义中说的 “以 ​​nums[i]​​​ 结尾”. 为了得到状态转移方程, 需要考察 ​​dp[i]​​​ 和其他元素的关系. 我们发现, 对于 ​​j < i​​,

  • 如果​​nums[i] > nums[j]​​​, 那么就可以在​​dp[j]​​​ 对应的最长递增子序列末尾, 将​​nums[i]​​​ 插入, 此时仍满足递增的性质, 这时候有​​dp[i] = dp[j] + 1 (nums[i] > nums[j])​​;
  • 而如果​​nums[i] <= nums[j]​​​, 说明​​nums[i]​​​ 无法加入到​​dp[j]​​​ 对应的最长递增子序列中, 又因为对于​​dp[i]​​​ 的定义中说的是需要 “以​​nums[i]​​​ 结尾”, 那么​​dp[i] = 1​​​, 表示此时以​​nums[i]​​​ 结尾的数组中的最长递增子序列其实就是​​nums[i]​​​ 本身, 大小为 1. (因此,​​dp​​​ 初始化时, 元素均设置为​​1​​ 很方便)

归纳上面的分析, 可以得到状态转移方程为:

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

因此代码如下:

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

return res;
}
};

举个例子, 下面列出数组 ​​nums​​ 以及数组中每个元素对应的 dp 值:

nums: 4, 10, 4, 3, 8, 9
dp: 1, 2, 1, 1, 2, 3

最后求出 ​​dp​​​ 中最大值为 ​​3​​​, 即 LIS 长度为 3, 比如 ​​3, 8, 9​​​ 或者 ​​4, 8, 9​​.

这道题的 ​​Follow up​​​ 中提到可以使用 ​​O(n log(n))​​ 的复杂度求解. 思路是尝试将数组中的最长递增子序列给找出来. 具体方法是:

使用序列 ​​r​​​ 来保存 ​​nums​​​ 中的最长递增子序列. 遍历 ​​nums​​​ 的每一个元素 ​​v​​​, 然后在数组 ​​r​​​ 中找到 ​​v​​​ 对应的 ​​lower_bound​​​, 即第一个大于或等于 ​​v​​ 的值.

  • 如果在序列​​r​​​ 中找不到​​v​​​, 说明​​v​​​ 比​​r​​​ 中的所有元素都大, 因此可以将​​v​​​ 加入到​​r​​ 的末尾,
  • 而如果​​r​​​ 中存在某元素(代码中用​​*p​​​ 表示)大于或等于​​v​​​, 那么用​​v​​​ 将这个元素替换, 这样的话, 一方面, 如果​​*p​​​ 原本就等于​​v​​​, 那么没任何影响; 而如果​​*p​​​ 原本大于​​v​​​, 那么此时更新成​​v​​ 后, 相当于数值变小了, 以后插入新的元素, 有更多得机会使得序列增长.

代码如下:

class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> r;

for(auto v : nums) {
auto p = std::lower_bound(r.begin(), r.end(), v);
if (r.end() == p)
r.push_back(v);
else
*p = v;
}
return r.size();
}
};