Skip to content

1155. Number of Dice Rolls With Target Sum 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int numRollsToTarget(int n, int k, int target) {
    constexpr int kMod = 1'000'000'007;
    vector<int> dp(target + 1);
    dp[0] = 1;

    while (n-- > 0) {  // n dices
      vector<int> newDp(target + 1);
      for (int i = 1; i <= k; ++i)           // numbers 1, 2, ..., f
        for (int t = i; t <= target; ++t) {  // all the possible targets
          newDp[t] += dp[t - i];
          newDp[t] %= kMod;
        }
      dp = std::move(newDp);
    }

    return dp[target];
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int numRollsToTarget(int n, int k, int target) {
    final int kMod = 1_000_000_007;
    int[] dp = new int[target + 1];
    dp[0] = 1;

    while (n-- > 0) { // n dices
      int[] newDp = new int[target + 1];
      for (int i = 1; i <= k; ++i)          // numbers 1, 2, ..., f
        for (int t = i; t <= target; ++t) { // all the possible targets
          newDp[t] += dp[t - i];
          newDp[t] %= kMod;
        }
      dp = newDp;
    }

    return dp[target];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def numRollsToTarget(self, n: int, k: int, target: int) -> int:
    kMod = 1_000_000_007
    dp = [1] + [0] * target

    for _ in range(n):  # n dices
      newDp = [0] * (target + 1)
      for i in range(1, k + 1):  # numbers 1, 2, ..., f
        for t in range(i, target + 1):  # all the possible targets
          newDp[t] += dp[t - i]
          newDp[t] %= kMod
      dp = newDp

    return dp[target]