// C# program for the above approach
using System;
public class ValidStrings {
// Define a 3D array for memoization
static long[, , ] dp = new long[10, 10, 100005];
// Define a modulo value
static int mod = (int)1e9 + 7;
// Recursive function to calculate the number of valid
// strings
static long CountValidString(int zeroCount,
int oneCount, int K1,
int K2, int n)
{
// Base case: If n becomes 0, return 1 as a valid
// record is found
if (n == 0)
return 1;
// If the result for the current state is already
// calculated, return it
if (dp[zeroCount, oneCount, n] != -1)
return dp[zeroCount, oneCount, n];
// Initialize variables to store different results
long res1 = 0, res2 = 0, res3 = 0;
// Iterate over three possible characters: 0, 1, and
// 2
for (int i = 0; i <= 2; i++) {
// Check if we can add '0' to the string
// (zeroCount < K1)
if (zeroCount < K1 && i == 0) {
res1 = CountValidString(zeroCount + 1, 0,
K1, K2, n - 1);
}
// Check if we can add '1' to the string
// (oneCount < K2)
if (oneCount < K2 && i == 1) {
res2 = CountValidString(
zeroCount, oneCount + 1, K1, K2, n - 1);
}
// Add '2' to the string
res3 = CountValidString(zeroCount, 0, K1, K2,
n - 1);
}
// Store the result in the memoization table and
// return the sum modulo 'mod'
return dp[zeroCount, oneCount, n]
= (res1 + res2 + res3) % mod;
}
// Main method
public static void Main(string[] args)
{
int n = 1012, K1 = 3, K2 = 5;
// Initialize the memoization table with -1
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = 0; k < 100005; k++) {
dp[i, j, k] = -1;
}
}
}
// Call the function to calculate the valid strings
Console.WriteLine(
CountValidString(0, 0, K1, K2, n));
}
}
// This code is contributed by Susobhan Akhuli