Problem solution · Python

Number of Ways to Build Sturdy Brick Wall

Number of Ways to Build Sturdy Brick Wall: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
42 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Number of Ways to Build Sturdy Brick Wall, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 42 lines of Python from the credited upstream file 2184.py.
  • The implementation visibly relies on sequence storage, cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeNumber of Ways to Build Sturdy Brick Wall · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def buildWall(self, height: int, width: int, bricks: list[int]) -> int:    MOD = 1_000_000_007    # Stores the valid rows in bitmask.    rows = []    self._buildRows(width, bricks, 0, rows)     n = len(rows)    # dp[i] := the number of ways to build `h` height walls with rows[i] in the bottom    dp = [1] * n    # graph[i] := the valid neighbors of rows[i]    graph = [[] for _ in range(n)]     for i, a in enumerate(rows):      for j, b in enumerate(rows):        if not a & b:          graph[i].append(j)     for _ in range(2, height + 1):      newDp = [0] * n      for i in range(n):        for v in graph[i]:          newDp[i] += dp[v]          newDp[i] %= MOD      dp = newDp     return sum(dp) % MOD   def _buildRows(      self,      width: int,      bricks: list[int],      path: int,      rows: list[int],  ):    for brick in bricks:      if brick == width:        rows.append(path)      elif brick < width:        newWidth = width - brick        self._buildRows(newWidth, bricks, path | 2 << newWidth, rows) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗