LeetCode 2189: Number of Ways to Build House of Cards Solution
Master LeetCode problem 2189 (Number of Ways to Build House of Cards), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2189. Number of Ways to Build House of Cards
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. Let's define a 2D array dp[i][j] to represent the number of ways to build a house of cards with i floors and j cards. The base case is dp[0][0] = 1.
To calculate dp[i][j], we need to consider two cases:
- If we use the current card to form the roof of the house, then the remaining cards can be used to build a house with
i-1floors andj-1cards. So,dp[i][j] += dp[i-1][j-1]. - If we use the current card to form the walls of the house, then the remaining cards can be used to build a house with
i-1floors andjcards. So,dp[i][j] += dp[i-1][j].
The final answer will be the sum of all dp[n][k], where n is the number of floors and k is the total number of cards.
Time Complexity:
The time complexity of this approach is O(n*k), where n is the number of floors and k is the total number of cards.
Space Complexity:
The space complexity of this approach is O(n*k) for the 2D array dp.
: :
Solution Code
class Solution {
public int buildHouseOfCards(int n, int k) {
int mod = (int)1e9 + 7;
int[][] dp = new int[n+1][k+1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
dp[i][j] = (dp[i-1][j-1] + dp[i-1][j]) % mod;
}
}
int ways = 0;
for (int i = 0; i <= k; i++) {
ways = (ways + dp[n][i]) % mod;
}
return ways;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2189 (Number of Ways to Build House of Cards)?
This page provides optimized solutions for LeetCode problem 2189 (Number of Ways to Build House of Cards) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2189 (Number of Ways to Build House of Cards)?
The time complexity for LeetCode 2189 (Number of Ways to Build House of Cards) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2189 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2189 in Java, C++, or Python.