|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +// Time Complexity : O(n * k * target), |
| 4 | +// where 'n', 'k' and 'target' are the variables used by the method. |
| 5 | +// For each dice, 'n', we check each values of 'target' to add the number of faces 'k' that can sum to 'target', |
| 6 | +// in a 3 layer nested for-loops. |
| 7 | +// |
| 8 | +// Space Complexity : O(n * target), |
| 9 | +// where 'n' and 'target' are the variables used by the method. |
| 10 | +// We use a matrix of 'n' rows with 'target' columns for tabulation. |
| 11 | + |
| 12 | +public class NumberOfDiceRollsWithTargetSum_Tabulation { |
| 13 | + |
| 14 | + // Approach: |
| 15 | + // A dynamic programming problem where there are overlapping subproblem, |
| 16 | + // for which each roll has possible 1 to k number face-up. |
| 17 | + // Here, the iterative and tabulation method is used. |
| 18 | + // By reducing the target by the face-up number each roll (hence n - 1), |
| 19 | + // the successful sequence of rolls is achieved when n = 0 and target = 0, which forms the base case for the table. |
| 20 | + |
| 21 | + public int numRollsToTarget(int n, int k, int target) { |
| 22 | + // As the array is 0-indexed, we need + 1 length to accommodate 'n' and 'target' respectively. |
| 23 | + int[][] table = new int[n + 1][target + 1]; |
| 24 | + // The seed/base case for successful sequence in the table. |
| 25 | + table[0][0] = 1; |
| 26 | + // Iterate through the table to get the result for all possibilities. |
| 27 | + int modulus = (int) (1e9 + 7); |
| 28 | + for (int i = 0; i < n; i++) { |
| 29 | + for (int j = 0; j < target; j++) { |
| 30 | + // Skip if the position in the array is 0, meaning nothing to add to the j + 1 to k positions. |
| 31 | + if (table[i][j] == 0) continue; |
| 32 | + for (int face = 1; face <= k; face++) { |
| 33 | + if (face + j <= target) { |
| 34 | + table[i + 1][j + face] = (table[i + 1][j + face] + table[i][j]) % modulus; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return table[n][target]; |
| 40 | + } |
| 41 | +} |
0 commit comments