forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0673-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
classSolution:
deffindNumberOfLIS(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
defdfs(i):
ifiindp:
returndp[i]
maxLen, maxCnt=1, 1# length and count of LIS
forjinrange(i+1, len(nums)):
ifnums[j] >nums[i]: # make sure increasing order
length, count=dfs(j)
iflength+1>maxLen:
maxLen, maxCnt=length+1, count
eliflength+1==maxLen:
maxCnt+=count
nonlocallenLIS, res
ifmaxLen>lenLIS:
lenLIS, res=maxLen, maxCnt
elifmaxLen==lenLIS:
res+=maxCnt
dp[i] = [maxLen, maxCnt]
returndp[i]
foriinrange(len(nums)):
dfs(i)
returnres
# 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
foriinrange(len(nums) -1, -1, -1):
maxLen, maxCnt=1, 1# len, cnt of LIS start from i
forjinrange(i+1, len(nums)):
ifnums[j] >nums[i]:
length, count=dp[j] # len, cnt of LIS start from j
iflength+1>maxLen:
maxLen, maxCnt=length+1, count
eliflength+1==maxLen:
maxCnt+=count
ifmaxLen>lenLIS:
lenLIS, res=maxLen, maxCnt
elifmaxLen==lenLIS:
res+=maxCnt
dp[i] = [maxLen, maxCnt]
returnres