|
| 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 | + // Recursive function with memoization to calculate the number of ways |
| 7 | + long long solve(int dice, int faces, int target, vector<vector<long long>>& dp) { |
| 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 no dice are left but the target is not 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 | + // Base case: If no dice are left and the target is zero, it's a valid way |
| 18 | + if (dice == 0 && target == 0) return 1; |
| 19 | + |
| 20 | + // If the current state has already been computed, return the stored result |
| 21 | + if (dp[dice][target] != -1) return dp[dice][target]; |
| 22 | + |
| 23 | + // Initialize the number of ways for the current state |
| 24 | + long long ans = 0; |
| 25 | + |
| 26 | + // Loop through all possible outcomes for a single dice roll |
| 27 | + for (int i = 1; i <= faces; i++) { |
| 28 | + // Recursively calculate the ways for the remaining dice and updated target |
| 29 | + ans = (ans + solve(dice - 1, faces, target - i, dp)) % MOD; |
| 30 | + } |
| 31 | + |
| 32 | + // Store the result in the dp table and return it |
| 33 | + return dp[dice][target] = ans; |
| 34 | + } |
| 35 | + |
| 36 | + // Function to calculate the number of ways to roll `n` dice with `k` faces to achieve `target` |
| 37 | + int numRollsToTarget(int n, int k, int target) { |
| 38 | + // Create a 2D dp table initialized with -1 to indicate uncomputed states |
| 39 | + vector<vector<long long>> dp(n + 1, vector<long long>(target + 1, -1)); |
| 40 | + |
| 41 | + // Call the recursive helper function with the initial values |
| 42 | + return solve(n, k, target, dp); |
| 43 | + } |
| 44 | +}; |
0 commit comments