#1411
Number of Ways to Paint N × 3 Grid
HardDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach utilizes dynamic programming to build solutions incrementally. By maintaining a record of the number of ways to paint each row based on the previous row's colors, we can efficiently compute the total configurations without redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the number of ways to paint the grid up to row i.
- 2Step 2: For each row, calculate the number of ways to paint it based on the previous row's configurations, ensuring no adjacent cells share the same color.
- 3Step 3: Use the relationship: dp[i] = 2 * dp[i-1] + 2 * dp[i-2] to build the solution.
solution.py14 lines
1# Full working Python code
2
3def countWays(n):
4 if n == 1:
5 return 12
6 dp = [0] * (n + 1)
7 dp[1] = 12
8 dp[2] = 30
9 for i in range(3, n + 1):
10 dp[i] = (2 * dp[i - 1] + 3 * dp[i - 2]) % (10**9 + 7)
11 return dp[n]
12
13# Example usage
14print(countWays(5000))ℹ
Complexity note: This complexity is efficient because we compute the number of ways to paint each row in a single pass, reusing previously computed results.
- 1Dynamic programming helps in breaking down the problem into smaller subproblems.
- 2Understanding the relationship between rows is crucial for efficient computation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.