Number of Ways to Build House of Cards — LeetCode 2189 Python Solution

MediumLeetCode PremiumMathDynamic Programming
Problem
#2189
Reading time
2 min

The problem

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.

Example

Input
n = 16
Output
2
Explanation
The two valid houses of cards are shown.

Python solution

Python
class Solution:
    def houseOfCards(self, n: int) -> int:
        @cache
        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)

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2189. Number of Ways to Build House of Cards is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2189. Number of Ways to Build House of Cards?
LeetCode 2189. Number of Ways to Build House of Cards is rated Medium on LeetCode.
What is the time complexity of LeetCode 2189. Number of Ways to Build House of Cards?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2189. Number of Ways to Build House of Cards?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 2189. Number of Ways to Build House of Cards cover?
LeetCode 2189. Number of Ways to Build House of Cards is tagged Math and Dynamic Programming on LeetCode.
Is LeetCode 2189. Number of Ways to Build House of Cards a premium problem?
Yes. LeetCode 2189. Number of Ways to Build House of Cards is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview