wiggle subsequence

这道题很类似于LIS的解法只是初始化的时候要tricky一点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class (object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return len(nums)
dp = [1 for _ in range(len(nums))]
dp_direction = [None for _ in range(len(nums))] # dp_direction[i] longest wiggle sequence ending with nums[i] with direction pos True or neg False
for i in range(1, len(nums)):
for j in range(i):
if dp_direction[j] is None:
if nums[i] > nums[j]:
dp_direction[i] = True
dp[i] = dp[j] + 1
if nums[i] < nums[j]:
dp_direction[i] = False
dp[i] = dp[j] + 1
elif nums[i] > nums[j] and not dp_direction[j]:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
dp_direction[i] = True
elif nums[i] < nums[j] and dp_direction[j]:
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
dp_direction[i] = False
return max(dp)