Number of Ways to Build House of Cards Problem
Description
LeetCode Problem 2189.
You are given an integer n representing the number of playing cards you have. A house of cards meets the following conditions:
- A house of cards consists of one or more rows of triangles and horizontal cards.
- Triangles are created by leaning two cards against each other.
- One card must be placed horizontally between all adjacent triangles in a row.
- Any triangle on a row higher than the first must be placed on a horizontal card from the previous row.
- Each triangle is placed in the leftmost available spot in the row.
Return the number of distinct house of cards you can build using all n cards. Two houses of cards are considered distinct if there exists a row where the two houses contain a different number of cards.
Example 1:

Input: n = 16
Output: 2
Explanation: The two valid houses of cards are shown.
The third house of cards in the diagram is not valid because the rightmost triangle on the top row is not placed on top of a horizontal card.
Example 2:

Input: n = 2
Output: 1
Explanation: The one valid house of cards is shown.
Example 3:

Input: n = 4
Output: 0
Explanation: The three houses of cards in the diagram are not valid.
The first house of cards needs a horizontal card placed between the two triangles.
The second house of cards uses 5 cards.
The third house of cards uses 2 cards.
Constraints:
1 <= n <= 500
Solution
Approach: Memoized Search Over Row Sizes
A row of t triangles takes 2t cards for the triangles and t - 1 cards to join neighbours, and the horizontal cards that sit on it cost one more per row above, so each row costs 3t - 1 cards in total. Every row must have strictly fewer triangles than the row below, so a house is simply a set of distinct values of t whose costs add up to n.
Let dfs(n, k) be the number of ways to spend exactly n cards using rows with at least k + 1 triangles. The row of size k + 1 costs x = 3k + 2. If x > n there is no way; if x == n there is one way; otherwise either use this row (dfs(n - x, k + 1)) or skip it (dfs(n, k + 1)). Memoize on (n, k).
Complexity: O(n2) time and space, since k is at most about n / 3.
from functools import lru_cache
class Solution:
def houseOfCards(self, n: int) -> int:
@lru_cache(None)
def dfs(n: int, k: int) -> int:
x = 3 * k + 2
if x > n:
return 0
if x == n:
return 1
return dfs(n - x, k + 1) + dfs(n, k + 1)
return dfs(n, 0)