LeetCode 1155: Number of Dice Rolls With Target Sum Solution
Master LeetCode problem 1155 (Number of Dice Rolls With Target Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1155. Number of Dice Rolls With Target Sum
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We create a 2D dp array where dp[i][j] represents the number of ways to get a sum of j using i dice. We then iterate through each dice and each possible sum to calculate the number of ways to reach that sum.
- Initialize a 2D dp array of size (n+1) x (target+1), where dp[i][j] represents the number of ways to get a sum of j using i dice.
- Base case: dp[0][0] = 1 (There is 1 way to get a sum of 0 using 0 dice).
- Iterate through each dice (i) from 1 to n and each possible sum (j) from 1 to target.
- For each dice and sum, calculate the number of ways to reach that sum by summing up the number of ways for all possible outcomes of the current dice roll.
- Return dp[n][target] % (10^9 + 7) as the final result.
Time Complexity: O(n * target * k) Space Complexity: O(n * target)
:
Solution Code
class Solution {
public int numRollsToTarget(int n, int k, int target) {
int mod = 1000000007;
int[][] dp = new int[n + 1][target + 1];
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= target; j++) {
for (int l = 1; l <= k; l++) {
if (j - l >= 0) {
dp[i][j] = (dp[i][j] + dp[i - 1][j - l]) % mod;
}
}
}
}
return dp[n][target];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1155 (Number of Dice Rolls With Target Sum)?
This page provides optimized solutions for LeetCode problem 1155 (Number of Dice Rolls With Target Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1155 (Number of Dice Rolls With Target Sum)?
The time complexity for LeetCode 1155 (Number of Dice Rolls With Target Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1155 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1155 in Java, C++, or Python.