Given a number n, count number of ways to fill a n x 4 grid using 1 x 4 tiles.
Input : n = 1 Output : 1 Input : n = 2 Output : 1 We can only place both tiles horizontally Input : n = 3 Output : 1 We can only place all tiles horizontally. Input : n = 4 Output : 2 The two ways are : 1) Place all tiles horizontally 2) Place all tiles vertically. Input : n = 5 Output : 3 We can fill a 5 x 4 grid in following ways : 1) Place all 5 tiles horizontally 2) Place first 4 vertically and 1 horizontally. 3) Place first 1 horizontally and 4 horizontally.
This problem is mainly an extension of this tiling problem
Let “count(n)” be the count of ways to place tiles on a “n x 4” grid, following two cases arise when we place the first tile.
- Place the first tile horizontally : If we place first tile horizontally, the problem reduces to “count(n-1)”
- Place the first tile vertically : If we place first tile vertically, then we must place 3 more tiles vertically. So the problem reduces to “count(n-4)”
Therefore, count(n) can be written as below.
count(n) = 1 if n = 1 or n = 2 or n = 3 count(n) = 2 if n = 4 count(n) = count(n-1) + count(n-4)
This recurrence is similar to Fibonacci Numbers and can be solved using Dynamic programming.
Count of ways is 3
Time Complexity : O(n)
Auxiliary Space : O(n)
This article is contributed by Rajat Jha. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Count the number of ways to tile the floor of size n x m using 1 x m size tiles
- Count number of ways to get Odd Sum
- Count the number of ways to traverse a Matrix
- Count number of ways to partition a set into k subsets
- Count number of ways to cover a distance
- Count number of ways to jump to reach end
- Count number of ways to reach a given score in a Matrix
- Count number of ways to reach a given score in a game
- Count number of ways to reach destination in a Maze
- Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors
- Count of different ways to express N as the sum of 1, 3 and 4
- Count ways to reach the n'th stair
- Count possible ways to construct buildings
- Count ways to build street under given constraints
- Count ways to reach a score using 1 and 2 with no consecutive 2s