Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 673 Number of Longest Increasing Subsequences - Walkthrough

Counting subsequences

Count LIS in [1,3,5,4,7][1, 3, 5, 4, 7]. Track dp[i]dp[i] = length, count[i]count[i] = number of LIS ending at ii. dp=[1,2,3,3,4]dp = [1, 2, 3, 3, 4]. For countcount: position 00 has 11. Position 11: extends from 00, so count[1]=1count[1] = 1.

Position 22: extends from 11, count[2]=1count[2] = 1. Position 33: extends from 11, count[3]=1count[3] = 1. Position 44: extends from 22 or 33 (both length 33), so count[4]=count[2]+count[3]=2count[4] = count[2] + count[3] = 2. Max length is 44 (only at position 44). Total LIS count: count[4]=2count[4] = 2. They are [1,3,5,7][1, 3, 5, 7] and [1,3,4,7][1, 3, 4, 7].