Dynamic Programming - Hard Level - Question 3
Leetcode 1955 Count Number of Special Subsequences
A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.
For example, [0,1,2] and [0,0,1,1,1,2] are special.
In contrast, [2,1,0], [1], and [0,1,2,0] are not special.
Given an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 2
Analysis:
For each element, there are three different choices: 0, 1, or 2.
Let focus on the 0 element first. If one element is 0, then there are two kinds of subsequences ending with 0:
A. the subsequences ending with previous 0's;
B. the subsequences ending with the current 0.
If we define a variable, sum0, to record the number of A, then number of B is sum0 + 1. Why?
Because
1. each of the previous subsequence can be combined with the current 0 to form a new subsequence, which gives the number of sum0 in total;
2. the current 0 itself can form a new subsequence, which gives 1.
When the current 0 becomes one of the previous 0's, we need to update sum0 = sum0 + (sum0 + 1), to make it include both A and B.
Similarly, we can obtain the following formula for the numbers of subsequences ending with 1 and 2.
sum1 = sum1 + (sum1 + sum0)
sum2 = sum2 + (sum2 + sum1)
See the code below:
class Solution {
public:
int countSpecialSubsequences(vector<int>& nums) {
long mod = 1e9+7, sum0 = 0, sum1 = 0, sum2 = 0;
int n = nums.size();
for(int i=1; i<=n; ++i) {
if(nums[i-1] == 0) {
// sum0: the number of subsequences ending with all previous 0s
// sum0 + 1: the number of subsequence ending with the current 0
sum0 += sum0 + 1;
sum0 %= mod;
}
else if(nums[i-1] == 1) {
// sum1: the number of subsequences ending with all previous 1s
// sum1 + sum0: the number of subsequence ending with the current 1
sum1 += sum1 + sum0;
sum1 %= mod;
}
else {
// sum2: the number of subsequences ending with all previous 2s
// sum2 + sum1: the number of subsequence ending with the current 2
sum2 += sum2 + sum1;
sum2 %= mod;
}
}
return sum2;
}
};
Comments
Post a Comment