Longest-Increasing-Subsequence
¶开始 Starting
Longest Increasing Subsequence
Algorithm by Sanjoy Dasgupta p. 171
https://leetcode.com/problems/longest-increasing-subsequence/
¶题目 Question
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]
.
¶想法 Thinking
基于Recursion,可以用 DP 节省时间,大概因为自己基础不太好的原因,听现在这个老师的讲课听得我很迷茫,于是准备重新搞一下这道题。
对于Dynamic Programming:课上总结了以下的general steps:
- Break problem into smaller subproblem
- Solve smaller subproblems first (bottom-up)
- Use information from smaller problem to solve a large subproblem
在这一题中,书上提供的思路为把input 看作是一个DAG (directed acyclic graph) $E$,每个node 是一个数字,对于这个DAG 上的node, 编上序号为 $a_{i}$ 和 $a_{j}$ ,edge 的创建条件如下(引用原文):
Establish a node i for each element ai , and add directed edges (i, j) whenever it is possible for ai and aj to be consecutive elements in an increasing subsequence, that is, whenever i < j and ai < aj
¶算法 Algorithm
for j = 1,2,3,…,n:
$L(j) = 1+max{L(i): (i,j) \in E}$
return $max_{j}L(j)$
即:
1 |
|
node 是否存在 由:if arr[i] > arr[j]
实现
max function是 由: lis[i]< lis[j] + 1
实现
¶运行时间 Run-time
$O(n^2)$
因为DP 是基于 recursion 上更改的(Iteration 版本每次iterate整个arr[0:i] for i< len(arr)。 DP 的优势在于 把每个node 的LIS result 都存到了一个array中,这样不需要重复计算已经计算过的sub-problem。
¶反思 Introspection
学习算法,光认真听课收获不会很大,结合书本,网络,油管对算法进行进一步的实现会有更大帮助
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!