Number of Binary Strings of length N with K adjacent Set Bits | Function to find the number of Bit Strings of length N with K adjacent set bits ; Base Case when we form bit string of length n ; if f ( bit string ) = k , count this way ; Check if the last bit was set , if it was set then call for next index by incrementing the adjacent bit count else just call the next index with same value of adjacent bit count and either set the bit at current index or let it remain unset ; set the bit at currentIndex ; unset the bit at currentIndex ; Driver Code ; total ways = ( ways by placing 1 st bit as 1 + ways by placing 1 st bit as 0 )
def waysToKAdjacentSetBits ( n , k , currentIndex , adjacentSetBits , lastBit ) : NEW_LINE INDENT if ( currentIndex == n ) : NEW_LINE INDENT if ( adjacentSetBits == k ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 NEW_LINE DEDENT noOfWays = 0 NEW_LINE if ( lastBit == 1 ) : NEW_LINE INDENT noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits + 1 , 1 ) ; NEW_LINE noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 0 ) ; NEW_LINE DEDENT elif ( lastBit != 1 ) : NEW_LINE INDENT noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 1 ) ; NEW_LINE noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 0 ) ; NEW_LINE DEDENT return noOfWays ; NEW_LINE DEDENT n = 5 ; k = 2 ; NEW_LINE totalWays = ( waysToKAdjacentSetBits ( n , k , 1 , 0 , 1 ) + waysToKAdjacentSetBits ( n , k , 1 , 0 , 0 ) ) ; NEW_LINE print ( " Number ▁ of ▁ ways ▁ = " , totalWays ) ; NEW_LINE