[LeetCode] Number of Dice Rolls With Target Sum

1155. Number of Dice Rolls With Target Sum

You have n dice and each die has k faces numbered from 1 to k.

Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
int dp[31][1001];
int mod = 1e9 + 7;
int helper(int n, int& k, int t) {
if(n == 0) return t == 0;
if(t <= 0) return 0;
if(dp[n][t] != -1) return dp[n][t];
dp[n][t] = 0;
int ma = min(k,t);
for(int i = 1; i <= ma; i++) {
dp[n][t] = (dp[n][t] + helper(n-1,k,t-i)) % mod;
}
return dp[n][t];
}
public:
int numRollsToTarget(int n, int k, int target) {
memset(dp,-1,sizeof(dp));
return helper(n,k,target);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/number-of-dice-rolls-with-target-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.