Skip to content

Commit 7c3c7ca

Browse files
authored
Create 03 - Bottom-Up | DP | Approach.cpp
1 parent f3fa5c6 commit 7c3c7ca

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Solution {
2+
public:
3+
// Constant to store the modulo value as the result can be large
4+
static const int MOD = 1e9 + 7;
5+
6+
// Function to calculate the number of ways to roll dice to achieve the target using bottom-up DP
7+
long long solve(int dice, int faces, int target) {
8+
// Base case: If the target becomes negative, it's not possible to achieve it
9+
if (target < 0) return 0;
10+
11+
// Base case: If there are no dice but the target is non-zero, it's an invalid configuration
12+
if (dice == 0 && target != 0) return 0;
13+
14+
// Base case: If there are dice left but the target is already zero, it's also invalid
15+
if (target == 0 && dice != 0) return 0;
16+
17+
// Create a 2D DP table where dp[d][t] represents the number of ways to achieve
18+
// the target `t` using `d` dice
19+
vector<vector<long long>> dp(dice + 1, vector<long long>(target + 1, 0));
20+
21+
// Initialize the base case: There is exactly one way to achieve a target of 0 with 0 dice
22+
dp[0][0] = 1;
23+
24+
// Iterate over the number of dice
25+
for (int d = 1; d <= dice; d++) {
26+
// Iterate over the target values
27+
for (int t = 1; t <= target; t++) {
28+
long long ans = 0;
29+
30+
// Consider each face value from 1 to `faces`
31+
for (int f = 1; f <= faces; f++) {
32+
// If the current target `t` is greater than or equal to the face value `f`,
33+
// add the number of ways to achieve the remaining target (t-f) with one less die
34+
if (t - f >= 0)
35+
ans = (ans + dp[d - 1][t - f]) % MOD;
36+
}
37+
38+
// Update the DP table for the current number of dice and target
39+
dp[d][t] = ans;
40+
}
41+
}
42+
43+
// Return the number of ways to achieve the target with the given number of dice
44+
return dp[dice][target];
45+
}
46+
47+
// Function to calculate the number of ways to roll `n` dice with `k` faces to achieve `target`
48+
int numRollsToTarget(int n, int k, int target) {
49+
// Call the helper function to solve the problem using bottom-up DP
50+
return solve(n, k, target);
51+
}
52+
};

0 commit comments

Comments
 (0)