Skip to content

Commit 0fe00e9

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 7c3c7ca commit 0fe00e9

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
public:
3+
// Constant to store the modulo value, used to handle large numbers
4+
static const int MOD = 1e9 + 7;
5+
6+
// Function to calculate the number of ways to roll dice to achieve the target using space-optimized 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 invalid
15+
if (target == 0 && dice != 0) return 0;
16+
17+
// Previous and current state arrays for space optimization
18+
// `prev` represents the number of ways to achieve a target with `d-1` dice
19+
// `curr` represents the number of ways to achieve a target with `d` dice
20+
vector<long long> prev(target + 1, 0);
21+
vector<long long> curr(target + 1, 0);
22+
23+
// Initialize the base case: There is exactly one way to achieve a target of 0 with 0 dice
24+
prev[0] = 1;
25+
26+
// Iterate over the number of dice
27+
for (int d = 1; d <= dice; d++) {
28+
// Iterate over the target values
29+
for (int t = 1; t <= target; t++) {
30+
long long ans = 0;
31+
32+
// Consider each face value from 1 to `faces`
33+
for (int f = 1; f <= faces; f++) {
34+
// If the current target `t` is greater than or equal to the face value `f`,
35+
// add the number of ways to achieve the remaining target (t-f) with one less die
36+
if (t - f >= 0)
37+
ans = (ans + prev[t - f]) % MOD;
38+
}
39+
40+
// Update the current state for the current target
41+
curr[t] = ans;
42+
}
43+
44+
// Move to the next dice: Copy `curr` to `prev` for the next iteration
45+
prev = curr;
46+
}
47+
48+
// Return the number of ways to achieve the target with the given number of dice
49+
return prev[target];
50+
}
51+
52+
// Function to calculate the number of ways to roll `n` dice with `k` faces to achieve `target`
53+
int numRollsToTarget(int n, int k, int target) {
54+
// Call the helper function to solve the problem using space-optimized DP
55+
return solve(n, k, target);
56+
}
57+
};

0 commit comments

Comments
 (0)