Number of Ways to Build House of Cards - 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
  • 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.

Input & Output

Example 1 — Small House
$ Input: n = 2
Output: 1
💡 Note: With 2 cards, we can only build one triangle (using both cards). This forms a single-row house.
Example 2 — Medium House
$ Input: n = 5
Output: 1
💡 Note: With 5 cards, we can build 2 triangles in one row (2+1+2 = 5 cards total). This is the only valid configuration.
Example 3 — Multiple Options
$ Input: n = 8
Output: 2
💡 Note: We can build: (1) 3 triangles in one row using all 8 cards, or (2) 2 triangles in first row (5 cards) + 1 triangle in second row (2 cards) + 1 card between levels.

Constraints

  • 1 ≤ n ≤ 500

Visualization

Tap to expand
House of Cards - DP Solution INPUT A K n = 2 2 cards available Build house of cards Triangle: 2 cards Horizontal: 1 card ALGORITHM STEPS 1 Define State dp[i] = ways with i cards 2 Base Case dp[0] = 1 (empty house) 3 Row Cards k triangles = 3k-1 cards 4 Recurrence Sum over all row sizes DP Table for n=2: dp[0] dp[2] 1 1 only 1 way FINAL RESULT The Only Valid House: 1 triangle = 2 cards Output: 1 OK - Verified Only 1 distinct way to use all 2 cards Key Insight: A row with k triangles needs 2k cards for triangles + (k-1) horizontal cards = 3k - 1 total cards. DP transitions: for each remaining cards, try all possible bottom row sizes. For n=2, only 1 triangle fits. TutorialsPoint - Number of Ways to Build House of Cards | Dynamic Programming Approach
Asked in
Google 15 Facebook 12
8.5K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen