




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.
1using System;
2
3public class Solution {
4    private static readonly int MOD = 1000000007;
5    public int NumRollsToTarget(int n, int k, int target) {
6        var memo = new int[n + 1, target + 1];
7        for (int i = 0; i <= n; i++)
8            for (int j = 0; j <= target; j++)
9                memo[i, j] = -1;
10        return Dfs(n, target, k, memo);
11    }
12
13    private int Dfs(int dice, int target, int k, int[,] memo) {
14        if (dice == 0) return target == 0 ? 1 : 0;
15        if (target <= 0) return 0;
16        if (memo[dice, target] != -1) return memo[dice, target];
17        int count = 0;
18        for (int i = 1; i <= k; ++i) {
19            count = (count + Dfs(dice - 1, target - i, k, memo)) % MOD;
20        }
21        return memo[dice, target] = count;
22    }
23
24    public static void Main() {
25        Solution sol = new Solution();
26        Console.WriteLine(sol.NumRollsToTarget(2, 6, 7)); // Output: 6
27    }
28}The C# solution uses memoization alongside recursion. The recursive Dfs method evaluates each dice roll path, storing results for each state configuration in the 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.
1
The DP table dp is built iteratively. For each dice i, calculate possible sums j using results from the previous dice count i-1 and adjusting the target by each face value x.