Skip to content

2189. Number of Ways to Build House of Cards

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int houseOfCards(int n) {
    // dp[i] := the number of valid result for i cards
    vector<int> dp(n + 1);
    dp[0] = 1;

    for (int baseCards = 2; baseCards <= n; baseCards += 3)
      for (int i = n; i >= baseCards; --i)
        // Use `baseCards` as the base, so we're left with `i - baseCards`
        // cards.
        dp[i] += dp[i - baseCards];

    return dp[n];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int houseOfCards(int n) {
    // dp[i] := the number of valid result for i cards
    int[] dp = new int[n + 1];
    dp[0] = 1;

    for (int baseCards = 2; baseCards <= n; baseCards += 3)
      for (int i = n; i >= baseCards; --i)
        // Use `baseCards` as the base, so we're left with `i - baseCards` cards.
        dp[i] += dp[i - baseCards];

    return dp[n];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def houseOfCards(self, n: int) -> int:
    # dp[i] := the number of valid result for i cards
    dp = [1] + [0] * n

    for baseCards in range(2, n + 1, 3):
      for i in range(n, baseCards - 1, -1):
        # Use `baseCards` as the base, so we're left with `i - baseCards` cards.
        dp[i] += dp[i - baseCards]

    return dp[n]