Number of Ways to Build House of Cards - Problem
Imagine you're a master card architect tasked with building intricate houses of cards using exactly n playing cards. But there are specific architectural rules you must follow!
A valid house of cards consists of multiple rows, where each row contains:
- Triangles: Formed by leaning two cards against each other (โณ)
- Horizontal cards: Placed between adjacent triangles in the same row for stability
The construction rules are:
- Each triangle requires exactly 2 cards
- Between every pair of adjacent triangles in a row, you must place 1 horizontal card
- Triangles in upper rows must be supported by horizontal cards from the row below
- All triangles are placed as far left as possible in each row
For example, a row with 3 triangles needs: 2ร3 = 6 cards for triangles + 2 horizontal cards between them = 8 total cards
Goal: Return the number of distinct ways to build a complete house of cards using all n cards. Two houses are different if any row contains a different number of cards.
Input & Output
example_1.py โ Basic House
$
Input:
n = 2
โบ
Output:
1
๐ก Note:
With 2 cards, we can only build 1 triangle (1 row with 1 triangle = 2 cards). Only 1 way possible.
example_2.py โ Medium House
$
Input:
n = 8
โบ
Output:
2
๐ก Note:
With 8 cards: Way 1: [3 triangles in 1 row] = 8 cards. Way 2: [1 triangle, then 1 triangle] = 2+2 cards (but this violates support rules). Actually: Way 1: [3 triangles] = 8 cards. Way 2: [2 triangles, then 1 triangle] = 5+2 = 7 cards (invalid). Only 1 way: single row with 3 triangles.
example_3.py โ Complex House
$
Input:
n = 16
โบ
Output:
5
๐ก Note:
Multiple valid configurations: 1) Single row with many triangles, 2) Two-row configurations, 3) Multi-row pyramids. Each represents a different architectural arrangement.
Constraints
- 1 โค n โค 500
- n represents the total number of playing cards available
- Each triangle requires exactly 2 cards
- Each horizontal separator requires exactly 1 card
Visualization
Tap to expand
Understanding the Visualization
1
Single Triangle
Start with 1 triangle (2 cards) - simplest house
2
Add Horizontal Card
Add 1 horizontal card to prepare for next triangle
3
Second Triangle
Add another triangle (2 more cards) = 5 total
4
Multi-row Option
Alternatively, build second row on top using horizontal cards as base
Key Takeaway
๐ฏ Key Insight: Each row configuration follows the formula 3k-1 cards for k triangles. Dynamic programming with memoization efficiently counts all valid multi-row combinations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code