g1901_2000.s1955_count_number_of_special_subsequences.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1901_2000.s1955_count_number_of_special_subsequences;
// #Hard #Array #Dynamic_Programming #2022_05_18_Time_22_ms_(80.65%)_Space_121_MB_(27.42%)
/**
* 1955 - Count Number of Special Subsequences\.
*
* Hard
*
* A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
*
* * 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** 109 + 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.
*
* **Example 1:**
*
* **Input:** nums = [0,1,2,2]
*
* **Output:** 3
*
* **Explanation:** The special subsequences are bolded [**0** , **1** , **2** ,2], [**0** , **1** ,2, **2** ], and [**0** , **1** , **2** , **2** ].
*
* **Example 2:**
*
* **Input:** nums = [2,2,0,0]
*
* **Output:** 0
*
* **Explanation:** There are no special subsequences in [2,2,0,0].
*
* **Example 3:**
*
* **Input:** nums = [0,1,2,0,1,2]
*
* **Output:** 7
*
* **Explanation:** The special subsequences are bolded:
*
* - [**0** , **1** , **2** ,0,1,2]
*
* - [**0** , **1** ,2,0,1, **2** ]
*
* - [**0** , **1** , **2** ,0,1, **2** ]
*
* - [**0** , **1** ,2,0, **1** , **2** ]
*
* - [**0** ,1,2, **0** , **1** , **2** ]
*
* - [**0** ,1,2,0, **1** , **2** ]
*
* - [0,1,2, **0** , **1** , **2** ]
*
* **Constraints:**
*
* * 1 <= nums.length <= 105
* * `0 <= nums[i] <= 2`
**/
public class Solution {
public int countSpecialSubsequences(int[] nums) {
int mod = 1000000007;
int[] dp = new int[] {1, 0, 0, 0};
for (int n : nums) {
dp[n + 1] = (dp[n] + 2 * dp[n + 1] % mod) % mod;
}
return dp[3];
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy