[
dp
array
]
Leetcode 1955. Count Number of Special Subsequences
Problem statement
https://leetcode.com/problems/count-number-of-special-subsequences/
Solution
Let dp[i] means number of longest increasing subsequences which end with i - 1, that is
dp[1]is for ending with0.dp[2]is for ending with1.dp[3]is for ending with2.
Then if new symbol is:
0, then we havedp[1] = 2*dp[1] + 1, because we extend all sequences of0here.1, then we havedp[2] = 2*dp[2] + dp[1], because we can extend all sequences of ends with0and1.2, then we havedp[3] = 2*dp[3] + dp[2], because we can extend all sequences of ends with1and2. Notice, that we can not extend ending with0, because we need to havej >= 1ones.
Complexity
It is O(n) for time and space.
Code
class Solution:
def countSpecialSubsequences(self, nums):
dp = [1, 0, 0, 0]
for i in nums:
dp[i+1] = (2*dp[i+1] + dp[i]) % (10**9 + 7)
return dp[-1]