76. Longest Increasing Subsequence

Description

Given a sequence of integers, find the longest increasing subsequence (LIS).

You code should return the length of the LIS.

Clarification

What's the definition of longest increasing subsequence?

The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Example

Example 1:

Input:  [5,4,1,2,3]

Output:  3

Explanation:

LIS is [1,2,3]

Example 2:

Input: [4,2,4,5,3,7]

Output:  4

Explanation:

LIS is [2,4,5,7]

Challenge

Time complexity O(n^2) or O(nlogn)

思路:

O(n2) 解法:

Dp[i] 表示以第i个数字为结尾的最长上升子序列的长度。

对于每个数字,枚举前面所有小于自己的数字 j,Dp[i] = max{Dp[j]} + 1. 如果没有比自己小的,Dp[i] = 1;

另外如果需要打印出最长上升子序列,就再开一个List存每个dp的值是从哪一个数算过来的,然后再逐个回溯得到最长的序列。

O(nlogn)解法:

使用一个辅助空间B数组。

B[i]存储Dp值为i的LIS中最大值最小的数字。(有多个位置,以这些位置为结尾的LIS长度都为i, 则这些数字中最小的一个存在B[i]中)

则B数组严格递增。且下标表示LIS长度,也是严格递增,可以在B数组中进行二分查找。

对于每个位置i,我们要找,所有小于A[i], 且Dp值最大的那个。这个操作在B数组中二分查找。(这个逻辑有点绕,等闲想不出来)

代码:

O(n2)的解法



你可能感兴趣的:(76. Longest Increasing Subsequence)