Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 673 · LIS

Number of Longest Increasing Subsequence

LeetCode 673 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Longer ⇒ copy the count; equal ⇒ add the count.

మధ్యస్థంArrayDynamic ProgrammingBinary Indexed TreeSegment TreeLongest Increasing Subsequence
LeetCode లో తెరవండి ↗

నేను 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. 1

    dp[i] = LIS length ending at i; count[i] = number of such sequences.

  2. 2

    For every j < i with nums[j] < nums[i]: compare dp[j] + 1 against dp[i].

  3. 3

    Longer: set dp[i] and copy count[j]. Equal: add count[j].

  4. 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 result
స్టెప్-త్రూ లోడ్ అవుతోంది…

Number 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.