Skip to content

Commit fd3baab

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 9c88b73 commit fd3baab

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the number of ways to roll the dice to achieve the target
4+
long long solve(int dice, int faces, int target) {
5+
// Base case: If the target becomes negative, it's not possible to achieve it
6+
if (target < 0) return 0;
7+
8+
// Base case: If no dice are left but the target is not zero, it's not a valid way
9+
if (dice == 0 && target != 0) return 0;
10+
11+
// Base case: If there are dice left but the target is zero, it's also invalid
12+
if (target == 0 && dice != 0) return 0;
13+
14+
// Base case: If no dice are left and the target is zero, it's a valid way
15+
if (dice == 0 && target == 0) return 1;
16+
17+
// Initialize a variable to store the number of ways
18+
long long ans = 0;
19+
20+
// Loop through all possible outcomes for a single dice roll
21+
for (int i = 1; i <= faces; i++) {
22+
// Recursively calculate the ways to achieve the remaining target
23+
// after rolling one die with the current face value `i`
24+
ans += solve(dice - 1, faces, target - i);
25+
}
26+
27+
// Return the total number of ways
28+
return ans;
29+
}
30+
31+
// Function to calculate the number of ways to roll `n` dice with `k` faces to achieve `target`
32+
int numRollsToTarget(int n, int k, int target) {
33+
// Call the helper recursive function
34+
return solve(n, k, target);
35+
}
36+
};

0 commit comments

Comments
 (0)