// C# program for the above approach
using System;
class GFG
{
// Function to return the number of total
// possible combinations of 0 and 1 to form
// an array of size N having sum of product
// of consecutive elements K
static int combinationsPossible(int N, int idx,
int prev, int val,
int K, int[, , ] dp)
{
// If value is greater than K, then
// return 0 as no combination is
// possible to have sum K
if (val > K) {
return 0;
}
// Check if the result of this recursive
// call is memoised already, if it is then
// just return the previously calculated result
if (dp[val, idx, prev] != -1) {
return dp[val, idx, prev];
}
// Check if the value is equal to K at N, if
// it is then return 1 as this combination
// is possible. Otherwise return 0.
if (idx == N - 1) {
if (val == K) {
return 1;
}
return 0;
}
int ans = 0;
// If previous element is 1
if (prev == 1) {
// If current element is 1 as well, then
// add 1 to value
ans += combinationsPossible(N, idx + 1, 1,
val + 1, K, dp);
// If current element is 0, then value
// will remain same
ans += combinationsPossible(N, idx + 1, 0, val,
K, dp);
}
// If previous element is 0, then value will
// remain same irrespective of the current element
else {
ans += combinationsPossible(N, idx + 1, 1, val,
K, dp);
ans += combinationsPossible(N, idx + 1, 0, val,
K, dp);
}
// Memoise and return the ans
return dp[val, idx, prev] = ans;
}
// Driver Code
public static void Main()
{
int N = 5;
int K = 3;
int[, , ] dp = new int[K + 1, N + 1, 2];
for (int i = 0; i < K + 1; i++)
for (int j = 0; j < N + 1; j++)
for (int l = 0; l < 2; l++)
dp[i, j, l] = -1;
// As the array can be started by 0 or 1, so take
// both cases while calculating the total possible
// combinations
Console.WriteLine(
combinationsPossible(N, 0, 0, 0, K, dp)
+ combinationsPossible(N, 0, 1, 0, K, dp));
}
}
// This code is contributed by ukasp.