Skip to content

Commit bba6de4

Browse files
committed
Sync LeetCode submission Runtime - 6 ms (23.38%), Memory - 19.6 MB (9.77%)
1 parent 05164d6 commit bba6de4

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>You have two types of tiles: a <code>2 x 1</code> domino shape and a tromino shape. You may rotate these shapes.</p>
2+
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/15/lc-domino.jpg" style="width: 362px; height: 195px;" />
3+
<p>Given an integer n, return <em>the number of ways to tile an</em> <code>2 x n</code> <em>board</em>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>
4+
5+
<p>In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<img alt="" src="https://assets.leetcode.com/uploads/2021/07/15/lc-domino1.jpg" style="width: 500px; height: 226px;" />
10+
<pre>
11+
<strong>Input:</strong> n = 3
12+
<strong>Output:</strong> 5
13+
<strong>Explanation:</strong> The five different ways are show above.
14+
</pre>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<pre>
19+
<strong>Input:</strong> n = 1
20+
<strong>Output:</strong> 1
21+
</pre>
22+
23+
<p>&nbsp;</p>
24+
<p><strong>Constraints:</strong></p>
25+
26+
<ul>
27+
<li><code>1 &lt;= n &lt;= 1000</code></li>
28+
</ul>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Approach 1: Dynamic Programming (Top-down)
2+
3+
# Time: O(n)
4+
# Space: O(n)
5+
6+
class Solution:
7+
def numTilings(self, n: int) -> int:
8+
MOD = 10 ** 9 + 7
9+
10+
@cache
11+
def p(n):
12+
if n == 2:
13+
return 1
14+
return (p(n - 1) + f(n - 2)) % MOD
15+
16+
@cache
17+
def f(n):
18+
if n <= 2:
19+
return n
20+
return (f(n - 1) + f(n - 2) + 2 * p(n - 1)) % MOD
21+
22+
return f(n)
23+

0 commit comments

Comments
 (0)