




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.
1import java.util.Arrays;
2
3class Solution {
4    private static final int MOD = 1000000007;
5    public int numRollsToTarget(int n, int k, int target) {
6        int[][] memo = new int[n + 1][target + 1];
7        for (int[] m : memo) Arrays.fill(m, -1);
8        return dfs(n, target, k, memo);
9    }
10
11    private int dfs(int dice, int target, int k, int[][] memo) {
12        if (dice == 0) return target == 0 ? 1 : 0;
13        if (target <= 0) return 0;
14        if (memo[dice][target] != -1) return memo[dice][target];
15        int count = 0;
16        for (int i = 1; i <= k; i++) {
17            count = (count + dfs(dice - 1, target - i, k, memo)) % MOD;
18        }
19        return memo[dice][target] = count;
20    }
21
22    public static void main(String[] args) {
23        Solution sol = new Solution();
24        System.out.println(sol.numRollsToTarget(2, 6, 7)); // Output: 6
25    }
26}Recursion with memoization keeps repeated states from being solved multiple times. Here, we use a 2D array for caching subproblem results, and utilize recursion to explore possibilities by adjusting dice counts and targets.
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.