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.