You are given an integer ‘N’ denoting the number of stairs. You have two colors: red and green. Count the number of ways to paint the stairs with colors red and green such that no two adjacent stairs have red colors painted on both of them.
Return the number of ways modulo 10^9 + 7.
Example:Input: ‘N’ = 2
Output: 3
The number of ways to paint the stairs is: (red, green), (green, red), (green, green), and (red, red). But two adjacent stairs cannot have the color red painted on both of them, (red, red) is not allowed.
Hence, there are 3 ways to paint 2 stairs.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains an integer number ‘N’’.
Output format :
For each test case, you don’t need to print anything just return the count of the number of ways to paint ‘N’ stairs.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
Time Limit: 1 sec
2
1
3
2
5
For the first case:
We can paint 1 stair with either green or red color. Hence the total number of ways to paint the colors is 2.
For the second case:
All valid ways to paint the stairs are (red, green, red), (green, red, green), (red, green, green), (green. green, red), and (green, green, green).
2
10
15
144
1597
Can you think of a way to explore all the ways recursively.
In the naive approach, we can recursively explore all the valid ways and then count each of the ways. We can use backtracking to find all the ways. For any ‘X’th stair if that stair is of color red then for the ‘X’+1th stair we have only one option and that is to color green. If that stair is of the color green then for the ‘X’+1th stair we have two options, either color it green or red.
So if colorStair(N, color) is our recursive function then :
If current stair is red:
colorStair(N, red) = colorStair(N-1, green)
Else
colorStair(N, green) = colorStair(N-1, red) + colorStair(N-1, green)
The base case of this recursive function is if ‘N’ = 0 then we have found a valid combination of colors, so return 1.
The steps are as follows:-
// Recursive function to explore all ways
function countWaysUtil( int n, int prevColor, int mod ):
function countWays( int n ):
O( 2^N ), Where ‘N’ is the number of stairs.
In the recursive function, if the color is green then we have two choices and we are exploring both of them. So the recursive calls are growing as 1, 2, 4, 8…. 2^N.
Hence the time complexity is O( 2^N ).
O( N )
The recursion stack will store at most ‘N’ function calls since the function backtracks after that.
Hence space complexity is O( N ).