![]() |
VOOZH | about |
Given a floor of size n x m and tiles of size 1 x m. The problem is to count the number of ways to tile the given floor using 1 x m tiles. A tile can either be placed horizontally or vertically.
Both n and m are positive integers and 2 < = m.
Examples:
Input : n = 2, m = 3
Output: 1
Explanation: Only one combination to place two tiles of size 1 x 3 horizontally on the floor of size 2 x 3.
Input : n = 4, m = 4
Output: 2
Explanation: There are two ways to tile the given floor. One way is to place 1 x 4 size of tile vertically and another one is to place them horizontally.
Table of Content
The idea is to recursively place tiles in all possible valid ways. At any step, there are two choices: place one tile horizontally, which reduces the remaining floor length by
1, or place a tile vertically, which occupiesmunits of length and reduces the remaining floor length bym. The total number of tilings is the sum of the ways obtained from these two choices.
n < m, only horizontal placement is possible → return 1n == m, two arrangements are possible: all horizontal and all vertical countWays(n - 1, m) and ways after placing tiles vertically, countWays(n - m, m)5
The idea is to optimize the recursive solution by storing the results of previously solved subproblems. For a floor of length
n, the number of ways depends on the answers for lengthsn-1andn-m. Since the same values are computed repeatedly in recursion, a DP array is used to memoize the results. Whenever a state is encountered again, the stored value is returned directly.
-1n < m, return 1n == m, return 2dp[n] is already computed, return it countWays(n - 1, m) and countWays(n - m, m)dp[n] and return it 10⁹ + 7 to avoid overflow5
The idea is to build the solution iteratively from smaller floor lengths to larger ones. Let
dp[i]represent the number of ways to tile a floor of lengthi. For every lengthi, there are two possibilities: place a tile horizontally, contributingdp[i-1]ways, or place tiles vertically, contributingdp[i-m]ways.
n + 1dp[i] = 1 when i < m and dp[i] = 2 when i == mi > m: dp[i] = dp[i-1] + dp[i-m]10⁹ + 7 after each computation dp[n]5