Number of Ways to Build Sturdy Brick Wall Problem
Description
LeetCode Problem 2184.
You are given integers height and width which specify the dimensions of a brick wall you are building. You are also given a 0-indexed array of unique integers bricks, where the i^th brick has a height of 1 and a width of bricks[i]. You have an infinite supply of each type of brick and bricks may not be rotated.
Each row in the wall must be exactly width units long. For the wall to be sturdy, adjacent rows in the wall should not join bricks at the same location, except at the ends of the wall.
Return the number of ways to build a sturdy wall. Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:

Input: height = 2, width = 3, bricks = [1,2]
Output: 2
Explanation:
The first two walls in the diagram show the only two ways to build a sturdy brick wall.
Note that the third wall in the diagram is not sturdy because adjacent rows join bricks 2 units from the left.
Example 2:
Input: height = 1, width = 1, bricks = [5]
Output: 0
Explanation:
There are no ways to build a sturdy wall because the only type of brick we have is longer than the width of the wall.
Constraints:
1 <= height <= 1001 <= width <= 101 <= bricks.length <= 101 <= bricks[i] <= 10- All the values of
bricksare unique.
Solution
Approach: Enumerate Rows, Then DP Over Compatible Rows
Width is at most 10, so we can list every way to fill one row with bricks by DFS. Two rows can sit on top of each other when their brick joints never line up, except at the two ends of the wall. Compute these joint positions with a two-pointer walk over both rows, and build a compatibility graph between rows. Then dp[i][j] is the number of ways to build i + 1 layers with the top layer being row pattern j: sum dp[i - 1][k] over every row k compatible with j. The answer is the sum of the last layer modulo 109 + 7.
Complexity: O(R2 * width + height * R2) time and O(R2) space, where R is the number of valid rows (at most 29 for width 10).
from collections import defaultdict
class Solution:
def buildWall(self, height: int, width: int, bricks: List[int]) -> int:
def dfs(v):
if v > width:
return
if v == width:
s.append(t[:])
return
for x in bricks:
t.append(x)
dfs(v + x)
t.pop()
def check(a, b):
s1, s2 = a[0], b[0]
i = j = 1
while i < len(a) and j < len(b):
if s1 == s2:
return False
if s1 < s2:
s1 += a[i]
i += 1
else:
s2 += b[j]
j += 1
return True
mod = 10**9 + 7
s = []
t = []
dfs(0)
g = defaultdict(list)
n = len(s)
for i in range(n):
if check(s[i], s[i]):
g[i].append(i)
for j in range(i + 1, n):
if check(s[i], s[j]):
g[i].append(j)
g[j].append(i)
dp = [[0] * n for _ in range(height)]
for j in range(n):
dp[0][j] = 1
for i in range(1, height):
for j in range(n):
for k in g[j]:
dp[i][j] += dp[i - 1][k]
dp[i][j] %= mod
return sum(dp[-1]) % mod