Skip to content

Commit 30b4e0a

Browse files
最长上升子序列
1 parent 6aa7cfa commit 30b4e0a

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

longest_increasing_sequence.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 问题简介
2+
最长公共上升子序列,longest increasing sequence,简称LCIS
3+
# 思路
4+
这个问题要由动态规划来解决,时间复杂度是O(n<sup>2</sup>),建立dp[n]和track[n]
5+
意义:
6+
----
7+
* dp[i]:以数据a[i]结尾的最长上升序列长度
8+
* track[i]:数据a[i]作为最长上升序列末项的前一项索引
9+
10+

longest_increasing_sequence.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#!/usr/bin/python
2+
#coding: utf-8
3+
4+
def isBiggerCompare(a, b):
5+
return a > b
6+
7+
def findLIS(sequence, compare = isBiggerCompare):
8+
n = len(sequence)
9+
dp = [0 for i in range(n)]
10+
track = [-1 for i in range(n)]
11+
ans = 1
12+
for i in range(1, n):
13+
MAX = 0
14+
for j in range(i):
15+
if compare(sequence[i], sequence[j]) and MAX < dp[j]:
16+
MAX = dp[j]
17+
track[i] = j
18+
# track[i] sequence[i]作为最长上升序列末项的前一项
19+
dp[i] = MAX + 1
20+
# dp[i] 以sequence[i]结尾的最长上升序列长度
21+
if dp[i] > dp[ans]:
22+
ans = i
23+
ansList = [sequence[ans]]
24+
while track[ans] != -1:
25+
ans = track[ans]
26+
ansList.insert(0, sequence[ans])
27+
return ansList
28+
29+
if __name__ == '__main__':
30+
s = [3, 1, 2, 1, 4, 3, 5]
31+
print findLIS(s)

0 commit comments

Comments
 (0)