Number of Longest Increasing Subsequence
LeetCode 673 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Longer ⇒ copy the count; equal ⇒ add the count.
நான் Number of Longest Increasing Subsequence (LeetCode 673) ஐ இப்படித் தீர்த்தேன் — LIS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
Approach
- 1
dp[i] = LIS length ending at i; count[i] = number of such sequences.
- 2
For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i].
- 3
Longer: set dp[i] and copy count[j]. Equal: add count[j].
- 4
Sum count[i] over all i whose dp[i] equals the overall max.
நான் எப்படித் தீர்த்தேன்
LIS with countsPythonO(n²) time · O(n) space
class Solution:
#1,3,5,4,7
def findNumberOfLIS(self, nums: List[int]) -> int:
dp=[1]*len(nums)
count=[1]*len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i]>nums[j]:
if dp[j]+1>dp[i]:
dp[i]=dp[j]+1
count[i]=count[j] #copy
elif dp[j]+1==dp[i]:
count[i]+=count[j] #add
lis=max(dp)
result=0
for i in range(len(nums)):
if dp[i]==lis:
result+=count[i]
return resultNumber of Longest Increasing Subsequence — அடிக்கடி கேட்கப்படும் கேள்விகள்
Number of Longest Increasing Subsequence பின்னாலுள்ள intuition என்ன?
Alongside the LIS length ending at each index, also count how many sequences reach that length. When an earlier element gives a strictly longer run, its count replaces ours; when it ties, its count adds to ours.
Number of Longest Increasing Subsequence (LeetCode 673) ஐ எப்படித் தீர்ப்பது?
1. dp[i] = LIS length ending at i; count[i] = number of such sequences. 2. For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i]. 3. Longer: set dp[i] and copy count[j]. Equal: add count[j]. 4. Sum count[i] over all i whose dp[i] equals the overall max.
Number of Longest Increasing Subsequence இன் time மற்றும் space complexity என்ன?
Time: O(n²). Space: O(n). (Accepted approach: LIS with counts.)
Number of Longest Increasing Subsequence இல் பொதுவான தவறுகள் என்ன?
Sum counts over every index that reaches the max length, not just the last one.