Count possible ways to construct buildings | C ++ program to count all possible way to construct buildings ; Returns count of possible ways for N sections ; Base case ; 2 for one side and 4 for two sides ; countB is count of ways with a building at the end countS is count of ways with a space at the end prev_countB and prev_countS are previous values of countB and countS respectively . Initialize countB and countS for one side ; Use the above recursive formula for calculating countB and countS using previous values ; Result for one side is sum of ways ending with building and ending with space ; Result for 2 sides is square of result for one side ; Driver program
#include <iostream> NEW_LINE using namespace std ; int countWays ( int N ) { if ( N == 1 ) return 4 ; int countB = 1 , countS = 1 , prev_countB , prev_countS ; for ( int i = 2 ; i <= N ; i ++ ) { prev_countB = countB ; prev_countS = countS ; countS = prev_countB + prev_countS ; countB = prev_countS ; } int result = countS + countB ; return ( result * result ) ; } int main ( ) { int N = 3 ; cout << " Count ▁ of ▁ ways ▁ for ▁ " << N << " ▁ sections ▁ is ▁ " << countWays ( N ) ; return 0 ; }