790. Domino and Tromino Tiling
MediumView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Approach
DP with recurrence dp[i] = 2·dp[i-1] + dp[i-3]; base cases dp[1]=1, dp[2]=2, dp[3]=5.
Key Techniques
Dynamic Programming
Dynamic programming solves problems by breaking them into overlapping sub-problems and storing results to avoid redundant work. The key steps are: define state, write a recurrence relation, set base cases, and choose top-down (memoization) or bottom-up (tabulation). DP often yields O(n²) → O(n) time improvements over brute force.
Matrix
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
790.cs
C#
// Approach: DP with recurrence dp[i] = 2·dp[i-1] + dp[i-3]; base cases dp[1]=1, dp[2]=2, dp[3]=5.
// Time: O(n) Space: O(n)
public class Solution
{
public int NumTilings(int n)
{
int MOD = 1_000_000_007;
long[] dp = new long[1001];
if (n >= 1)
dp[1] = 1;
if (n >= 2)
dp[2] = 2;
if (n >= 3)
dp[3] = 5;
for (int i = 4; i <= n; ++i)
dp[i] = (2 * dp[i - 1] + dp[i - 3]) % MOD;
return (int)dp[n];
}
}Advertisement
Was this solution helpful?