forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dice-roll-simulation.cpp
45 lines (44 loc) · 1.49 KB
/
dice-roll-simulation.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
40
41
42
43
44
45
// Time: O(m * n), m is the max of rollMax
// Space: O(m)
class Solution {
public:
int dieSimulator(int n, vector<int>& rollMax) {
static const int MOD = 1e9 + 7;
vector<vector<int>> dp;
for (int i = 0; i < 6; ++i) {
dp.emplace_back(rollMax[i]);
dp[i][0] = 1; // 0-indexed
}
while (--n) {
vector<vector<int>> new_dp;
for (int i = 0; i < 6; ++i) {
new_dp.emplace_back(rollMax[i]);
}
for (int i = 0; i < 6; ++i) {
for (int k = 0; k < rollMax[i]; ++k) {
for (int j = 0; j < 6; ++j) {
if (i == j) {
if (k < rollMax[i] - 1) { // 0-indexed
new_dp[j][k + 1] = (new_dp[j][k + 1] + dp[i][k]) % MOD;
}
} else {
new_dp[j][0] = (new_dp[j][0] + dp[i][k]) % MOD;
}
}
}
}
dp = move(new_dp);
}
uint64_t result = 0;
for (const auto& row : dp) {
const auto& total =
accumulate(row.cbegin(), row.cend(),
0ull,
[&](const auto& a, const auto& b) {
return (a + b) % MOD;
});
result = (result + total) % MOD;
}
return result;
}
};