forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0673-number-of-longest-increasing-subsequence.py
54 lines (45 loc) · 1.85 KB
/
0673-number-of-longest-increasing-subsequence.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
# 1. O(n^2) Recursive solution with Caching
dp = {} # key = index, value = [length of LIS, count]
lenLIS, res = 0, 0 # length of LIS, count of LIS
def dfs(i):
if i in dp:
return dp[i]
maxLen, maxCnt = 1, 1 # length and count of LIS
for j in range(i + 1, len(nums)):
if nums[j] > nums[i]: # make sure increasing order
length, count = dfs(j)
if length + 1 > maxLen:
maxLen, maxCnt = length + 1, count
elif length + 1 == maxLen:
maxCnt += count
nonlocal lenLIS, res
if maxLen > lenLIS:
lenLIS, res = maxLen, maxCnt
elif maxLen == lenLIS:
res += maxCnt
dp[i] = [maxLen, maxCnt]
return dp[i]
for i in range(len(nums)):
dfs(i)
return res
# 2. O(n^2) Dynamic Programming
dp = {} # key = index, value = [length of LIS, count]
lenLIS, res = 0, 0 # length of LIS, count of LIS
# i = start of subseq
for i in range(len(nums) - 1, -1, -1):
maxLen, maxCnt = 1, 1 # len, cnt of LIS start from i
for j in range(i + 1, len(nums)):
if nums[j] > nums[i]:
length, count = dp[j] # len, cnt of LIS start from j
if length + 1 > maxLen:
maxLen, maxCnt = length + 1, count
elif length + 1 == maxLen:
maxCnt += count
if maxLen > lenLIS:
lenLIS, res = maxLen, maxCnt
elif maxLen == lenLIS:
res += maxCnt
dp[i] = [maxLen, maxCnt]
return res