Count binary strings with k times appearing adjacent two set bits | Python3 program to count number of binary strings with k times appearing consecutive 1 's. ; 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. ; If n = 1 and k = 0. ; number of adjacent 1 's can not exceed i-1 ; Driver Code
def countStrings ( n , k ) : NEW_LINE INDENT dp = [ [ [ 0 , 0 ] for __ in range ( k + 1 ) ] for _ in range ( n + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ 0 ] = ( dp [ i - 1 ] [ j ] [ 0 ] + dp [ i - 1 ] [ j ] [ 1 ] ) NEW_LINE dp [ i ] [ j ] [ 1 ] = dp [ i - 1 ] [ j ] [ 0 ] NEW_LINE if j >= 1 : NEW_LINE INDENT dp [ i ] [ j ] [ 1 ] += dp [ i - 1 ] [ j - 1 ] [ 1 ] NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ k ] [ 0 ] + dp [ n ] [ k ] [ 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE print ( countStrings ( n , k ) ) NEW_LINE DEDENT