leetcode300 Longest Increasing Subsequence

 1 """
 2 Given an unsorted array of integers, find the length of longest increasing subsequence.
 3 Example
 4 Input: [10,9,2,5,3,7,101,18]
 5 Output: 4
 6 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
 7 """
 8 """
 9 类似于139,322
10 自己找到了动态规划方程
11 f(i) = 1 + max(f(j) if nums[i] > nums[j]) (j < i)
12 特别注意的是将数组初始化为1
13 """
14 class Solution:
15     def lengthOfLIS(self, nums):
16         if not nums: #bug nums == None 无法通过 nums = []的情况
17             return 0
18         dp = [1] * (len(nums)+1)
19         for i in range(1, len(nums)):
20             for j in range(i):
21                 if nums[j] < nums[i]:
22                     dp[i] = max(dp[i], dp[j] + 1)
23         return max(dp)
24 
25 # nums1 = None
26 # nums2 = []
27 # if nums1 == None:
28 #     print('1')
29 # if not nums1:
30 #     print('2')
31 # if nums2 == None: #针对这种情况无法判断nums=[]
32 #     print('3')
33 # if not nums2:
34 #     print('4')
35 # #Answer 为 1 2 4

猜你喜欢

转载自www.cnblogs.com/yawenw/p/12319221.html