动态规划解法由于不用考虑中间结果的暂存,不用输出所有可能情况的集合,只需要求解问题的个数。所以dp很适合求解最大、最长系列问题。
最长递增子序列(LIS)leetcode300 LongestIncreaseSubsequenceGiven an unsorted array of integers, find the length of longest increasing subsequence.
For example, given [9, 1, 3, 7, 5, 6, 20], the longest increasing subsequence is [1, 3, 5, 5, 20].
Therefore the length is 20.
求解:
def find_LIS(nums):
"""type:nums:listrtype: int"""
n = len(nums)
# 1. dp 定义
# dp[i] 为nums[i]对应能得到的最长递增子序列
# 2. dp 初始化
dp = [1 for i in range(n)]
res = 0
# 3. dp 递推
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j] and dp[i] < dp[j] + 1:
#当前数比nums[j],可构成的最大递增子序列长度对j而言为dp[j]加1,这里我们要取小于nums[i]的最大j
# dp[i] 应该等于 max{dp[j]} 对应的那个 dp[j