MediumNo. 2189LeetCode Premium

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

Topics
Math, Dynamic Programming
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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(n2)

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

Related problems
No.ProblemDifficulty
0062Unique PathsMedium
0070Climbing StairsEasy
0096Unique Binary Search TreesMedium
0233Number of Digit OneHard
0241Different Ways to Add ParenthesesMedium
0279Perfect SquaresMedium

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(n2).

What is the space complexity of LeetCode 2189. Number of Ways to Build House of Cards?

The Python solution on this page uses O(n2) 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.

Free to download. Check it runs on your machine, then pick a plan.