forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-ways-to-build-house-of-cards.cpp
39 lines (37 loc) · 1.12 KB
/
number-of-ways-to-build-house-of-cards.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Time: O(n^2)
// Space: O(n)
// dp
class Solution {
public:
int houseOfCards(int n) {
vector<int> dp(n + 1); // dp[i]: number of ways with i cards and at most t triangles in the first row
dp[0] = 1;
for (int t = 1; t <= (n + 1) / 3; ++t) {
for (int i = n; i >= 3 * t - 1; --i) {
dp[i] += dp[i - (3 * t - 1)];
}
}
return dp[n];
}
};
// Time: O(n^3)
// Space: O(n^2)
// dp
class Solution_TLE {
public:
int houseOfCards(int n) {
vector<vector<int>> dp((n + 1) / 3 + 1, vector<int>(n + 1)); // dp[t][i]: number of ways with i cards and t triangles in the lowest row
dp[0][0] = 1;
for (int t = 1; t <= (n + 1) / 3; ++t) {
for (int i = 3 * t - 1; i <= n; ++i) {
for (int j = 0; j < t; ++j) {
dp[t][i] += dp[j][i - (3 * t - 1)];
}
}
}
return accumulate(cbegin(dp), cend(dp), 0,
[](const auto& total, const auto& x) {
return total + x.back();
});
}
};