Skip to content

Commit 5e8a4ad

Browse files
author
YuChengKai
committed
最长递增子序列
1 parent a13e6e0 commit 5e8a4ad

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Algorithm/algorithm-ch.md

+39
Original file line numberDiff line numberDiff line change
@@ -828,3 +828,42 @@ function knapsack(w, v, C) {
828828
}
829829
```
830830

831+
## 最长递增子序列
832+
833+
最长递增子序列意思是在一组数字中,找出最长一串递增的数字,比如
834+
835+
0, 3, 4, 17, 2, 8, 6, 10
836+
837+
对于以上这串数字来说,最长递增子序列就是 0, 3, 4, 8, 10,可以通过以下表哥更清晰的理解
838+
839+
| 数字 | 0 | 3 | 4 | 17 | 2 | 8 | 6 | 10 |
840+
| :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: | :--: |
841+
| 长度 | 1 | 2 | 3 | 4 | 2 | 4 | 4 | 5 |
842+
843+
通过以上表格可以很清晰的发现一个规律,找出刚好比当前数字小的数,并且在小的数组成的长度基础上加一。
844+
845+
这个问题的动态思路解法很简单,直接上代码
846+
847+
```js
848+
function lis(n) {
849+
if (n.length === 0) return 0
850+
// 创建一个和参数相同大小的数组,并填充值为 1
851+
let array = new Array(n.length).fill(1)
852+
// 从索引 1 开始遍历,因为数组已经所有都填充为 1 了
853+
for (let i = 1; i < n.length; i++) {
854+
// 从索引 0 遍历到 i
855+
// 判断索引 i 上的值是否大于之前的值
856+
for (let j = 0; j < i; j++) {
857+
if (n[i] > n[j]) {
858+
array[i] = Math.max(array[i], 1 + array[j])
859+
}
860+
}
861+
}
862+
let res = 1
863+
for (let i = 0; i < array.length; i++) {
864+
res = Math.max(res, array[i])
865+
}
866+
return res
867+
}
868+
```
869+

0 commit comments

Comments
 (0)