Cuente strings binarias con k veces que aparecen adyacentes a dos bits establecidos

Dados dos enteros n y k, cuente el número de strings binarias de longitud n con k como el número de veces que aparecen unos adyacentes.

Ejemplos: 

Input  : n = 5, k = 2
Output : 6
Explanation:
Binary strings of length 5 in which k number of times
two adjacent set bits appear.
00111  
01110
11100
11011
10111
11101

Input  : n = 4, k = 1
Output : 3
Explanation:
Binary strings of length 3 in which k number of times
two adjacent set bits appear.
0011  
1100
0110

Intentemos escribir la función recursiva para la declaración del problema anterior: 
1) n = 1, solo existen dos strings binarias con longitud 1, que no tienen ningún 1 adyacente 
      String 1: «0» 
      String 2: «1»
2) Para todo n > 1 y todo k, surgen dos casos 
      a) Strings que terminan en 0: la string de longitud n se puede crear agregando 0 a todas las strings de longitud n-1 que tienen k por dos 1 adyacentes que terminan en 0 y 1 (que tienen 0 en n La ‘ésima posición no cambiará el conteo de 1’s adyacentes). 
      b) Strings que terminan en 1: la string de longitud n se puede crear agregando 1 a todas las strings de longitud n-1 que tienen k veces 1 adyacentes y terminan en 0 y a todas las strings delongitud n-1 que tiene k-1 1 adyacentes y termina en 1 .

Ejemplo: sea s = 011, es decir, una string que termina en 1 y tiene un conteo adyacente como 1. Al agregarle 1, s = 0111 aumenta el conteo de 1 adyacente.  

Let there be an array dp[i][j][2] where dp[i][j][0]
denotes number of binary strings with length i having
j number of two adjacent 1's and ending with 0.
Similarly dp[i][j][1] denotes the same binary strings
with length i and j adjacent 1's but ending with 1.
Then: 
    dp[1][0][0] = 1 and dp[1][0][1] = 1
    For all other i and j,
        dp[i][j][0] = dp[i-1][j][0] + dp[i-1][j][1]
        dp[i][j][1] = dp[i-1][j][0] + dp[i-1][j-1][1]

Then, output dp[n][k][0] + dp[n][k][1]

C++

// C++ program to count number of binary strings
// with k times appearing consecutive 1's.
#include <bits/stdc++.h>
using namespace std;
 
int countStrings(int n, int k)
{
    // dp[i][j][0] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 0.
    // dp[i][j][1] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 1.
    int dp[n + 1][k + 1][2];
    memset(dp, 0, sizeof(dp));
 
    // If n = 1 and k = 0.
    dp[1][0][0] = 1;
    dp[1][0][1] = 1;
 
    for (int i = 2; i <= n; i++) {
 
        // number of adjacent 1's can not exceed i-1
        for (int j = 0; j <= k; j++) {
            dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1];
            dp[i][j][1] = dp[i - 1][j][0];
 
            if (j - 1 >= 0)
                dp[i][j][1] += dp[i - 1][j - 1][1];
        }
    }
 
    return dp[n][k][0] + dp[n][k][1];
}
 
// Driver code
int main()
{
    int n = 5, k = 2;
    cout << countStrings(n, k);
    return 0;
}

Java

// Java program to count number of binary strings
// with k times appearing consecutive 1's.
class GFG {
 
    static int countStrings(int n, int k)
    {
        // dp[i][j][0] stores count of binary
        // strings of length i with j consecutive
        // 1's and ending at 0.
        // dp[i][j][1] stores count of binary
        // strings of length i with j consecutive
        // 1's and ending at 1.
        int dp[][][] = new int[n + 1][k + 1][2];
 
        // If n = 1 and k = 0.
        dp[1][0][0] = 1;
        dp[1][0][1] = 1;
 
        for (int i = 2; i <= n; i++) {
 
            // number of adjacent 1's can not exceed i-1
            for (int j = 0; j < i && j < k + 1; j++) {
                dp[i][j][0] = dp[i - 1][j][0] + dp[i - 1][j][1];
                dp[i][j][1] = dp[i - 1][j][0];
 
                if (j - 1 >= 0) {
                    dp[i][j][1] += dp[i - 1][j - 1][1];
                }
            }
        }
 
        return dp[n][k][0] + dp[n][k][1];
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 5, k = 2;
        System.out.println(countStrings(n, k));
    }
}
 
// This code has been contributed by 29AjayKumar

Python3

# Python3 program to count number of
# binary strings with k times appearing
# consecutive 1's.
def countStrings(n, k):
 
    # dp[i][j][0] stores count of binary
    # strings of length i with j consecutive
    # 1's and ending at 0.
    # dp[i][j][1] stores count of binary
    # strings of length i with j consecutive
    # 1's and ending at 1.
    dp = [[[0, 0] for __ in range(k + 1)]
                  for _ in range(n + 1)]
 
    # If n = 1 and k = 0.
    dp[1][0][0] = 1
    dp[1][0][1] = 1
 
    for i in range(2, n + 1):
         
        # number of adjacent 1's can not exceed i-1
        for j in range(k + 1):
            dp[i][j][0] = (dp[i - 1][j][0] +
                           dp[i - 1][j][1])
            dp[i][j][1] = dp[i - 1][j][0]
            if j >= 1:
                dp[i][j][1] += dp[i - 1][j - 1][1]
 
    return dp[n][k][0] + dp[n][k][1]
 
# Driver Code
if __name__ == '__main__':
    n = 5
    k = 2
    print(countStrings(n, k))
 
# This code is contributed by vibhu4agarwal

C#

// C# program to count number of binary strings
// with k times appearing consecutive 1's.
using System;
 
class GFG {
 
    static int countStrings(int n, int k)
    {
        // dp[i][j][0] stores count of binary
        // strings of length i with j consecutive
        // 1's and ending at 0.
        // dp[i][j][1] stores count of binary
        // strings of length i with j consecutive
        // 1's and ending at 1.
        int[,, ] dp = new int[n + 1, k + 1, 2];
 
        // If n = 1 and k = 0.
        dp[1, 0, 0] = 1;
        dp[1, 0, 1] = 1;
 
        for (int i = 2; i <= n; i++) {
 
            // number of adjacent 1's can not exceed i-1
            for (int j = 0; j < i && j < k + 1; j++) {
                dp[i, j, 0] = dp[i - 1, j, 0] + dp[i - 1, j, 1];
                dp[i, j, 1] = dp[i - 1, j, 0];
 
                if (j - 1 >= 0) {
                    dp[i, j, 1] += dp[i - 1, j - 1, 1];
                }
            }
        }
 
        return dp[n, k, 0] + dp[n, k, 1];
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 5, k = 2;
        Console.WriteLine(countStrings(n, k));
    }
}
 
// This code contributed by Rajput-Ji

PHP

<?php
// PHP program to count number of binary strings
// with k times appearing consecutive 1's.
 
function countStrings($n, $k)
{
    // dp[i][j][0] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 0.
    // dp[i][j][1] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 1.
    $dp=array_fill(0, $n + 1, array_fill(0, $k + 1, array_fill(0, 2, 0)));
 
    // If n = 1 and k = 0.
    $dp[1][0][0] = 1;
    $dp[1][0][1] = 1;
 
    for ($i = 2; $i <= $n; $i++)
    {
        // number of adjacent 1's can not exceed i-1
        for ($j = 0; $j < $i; $j++)
        {
            if(isset($dp[$i][$j][0])||isset($dp[$i][$j][1])){
              $dp[$i][$j][0] = $dp[$i - 1][$j][0] + $dp[$i - 1][$j][1];
              $dp[$i][$j][1] = $dp[$i - 1][$j][0];
            }
            if ($j - 1 >= 0 && isset($dp[$i][$j][1]))
                $dp[$i][$j][1] += $dp[$i - 1][$j - 1][1];
        }
    }
 
    return $dp[$n][$k][0] + $dp[$n][$k][1];
}
 
// Driver code
$n=5;
$k=2;
echo countStrings($n, $k);
     
// This code is contributed by mits
?>

Javascript

<script>
 
// Javascript program to count number
// of binary strings with k times
// appearing consecutive 1's.
function countStrings(n, k)
{
     
    // dp[i][j][0] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 0.
    // dp[i][j][1] stores count of binary
    // strings of length i with j consecutive
    // 1's and ending at 1.
    let dp = new Array(n + 1);
    for(let i = 0; i < n + 1; i++)
    {
        dp[i] = new Array(k + 1);
        for(let j = 0; j < k + 1; j++)
        {
            dp[i][j] = new Array(2);
            for(let l = 0 ; l < 2; l++)
            {
                dp[i][j][l] = 0;
            }
        }
    }
 
    // If n = 1 and k = 0.
    dp[1][0][0] = 1;
    dp[1][0][1] = 1;
 
    for(let i = 2; i <= n; i++)
    {
         
        // Number of adjacent 1's can not exceed i-1
        for(let j = 0; j < i && j < k + 1; j++)
        {
            dp[i][j][0] = dp[i - 1][j][0] +
                          dp[i - 1][j][1];
            dp[i][j][1] = dp[i - 1][j][0];
 
            if (j - 1 >= 0)
            {
                dp[i][j][1] += dp[i - 1][j - 1][1];
            }
        }
    }
    return dp[n][k][0] + dp[n][k][1];
}
 
// Driver code
let n = 5, k = 2;
 
document.write(countStrings(n, k));
 
// This code is contributed by rag2127
 
</script>

Producción: 

6

Complejidad del tiempo : O(n 2 )

Espacio Auxiliar: O(n 2 )

Este artículo es una contribución de Aarti_Rathi y Ekta Goel . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *