Count Number of Special Subsequences LeetCode solution in Java
1class Solution {2public int countSpecialSubsequences(int[] nums) {3long z = 0; // starting and ending with zero4long zo = 0; // starting with zero and ending with One5long zot = 0; // starting with zero and ending Two6int mod = 1000000007;7for (int i : nums) {8if (i == 0) {9z = ((2 * z) % mod + 1) % mod; // zero = 2*zero+110} else if (i == 1) {11zo = ((2 * zo) % mod + z % mod) % mod; // zero = 2*zeroOne+zero12} else {13zot = ((2 * zot) % mod + zo % mod) % mod; // zeroOneTwo = 2*zeroOneTwo+zeroOne14}15}16return (int) (zot % mod);17}18}