
Sponsored
Sponsored
We utilize recursion to explore different combinations of dice rolls to reach the target sum. For every die, we try all face values and keep track of the sum formed. To avoid redundant calculations, we use memoization.
Time Complexity: O(n * target * k) because there are n * target states and we iterate up to k times in the worst case.
Space Complexity: O(n * target) for the memoization table.
1const MOD = 1000000007;
2
3function numRollsToTarget(n, k, target) {
4 const memo = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-1));
5
6 function dfs(dice, target) {
7 if (dice === 0) return target === 0 ? 1 : 0;
8 if (target <= 0) return 0;
9 if (memo[dice][target] !== -1) return memo[dice][target];
10 let count = 0;
11 for (let i = 1; i <= k; i++) {
12 count = (count + dfs(dice - 1, target - i)) % MOD;
13 }
14 memo[dice][target] = count;
15 return count;
16 }
17 return dfs(n, target);
18}
19
20console.log(numRollsToTarget(2, 6, 7)); // Output: 6The JavaScript solution defines a recursive function calling different face values for available dice, caching results as it builds those through a memo array.
Use a Dynamic Programming (DP) table where dp[i][j] represents the number of ways to achieve sum j with i dice. Initially, only dp[0][0] = 1 since there's one way to roll zero dice to get zero sum. The state transition iterates over each dice and accumulates ways using previous results.
Time Complexity: O(n * target * k) due to nested loops.
Space Complexity: O(n * target) for the DP table.
public class Solution {
public int NumRollsToTarget(int n, int k, int target) {
const int MOD = 1000000007;
int[,] dp = new int[n + 1, target + 1];
dp[0, 0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= target; j++) {
for (int x = 1; x <= k; x++) {
if (j >= x) {
dp[i, j] = (dp[i, j] + dp[i - 1, j - x]) % MOD;
}
}
}
}
return dp[n, target];
}
public static void Main() {
Solution sol = new Solution();
Console.WriteLine(sol.NumRollsToTarget(2, 6, 7)); // Output: 6
}
}DP table builds progressively from baseline dice configurations summed over potential achievable numbers. The combined effect allows cumulative state transitioning for result evaluation.