#1155

Number of Dice Rolls With Target Sum

Medium
Dynamic ProgrammingDynamic ProgrammingMemoization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(k^n)
O(n * target * k)
Space
O(n)
O(n * target)
💡

Intuition

Time O(n * target * k)Space O(n * target)

Using dynamic programming, we can build a table that keeps track of the number of ways to achieve each possible sum with a certain number of dice. This avoids redundant calculations and significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a 2D DP array where dp[i][j] represents the number of ways to achieve sum j with i dice.
  2. 2Step 2: Initialize dp[0][0] to 1 (base case: 0 dice can only achieve sum 0).
  3. 3Step 3: Iterate through each die and each possible sum, updating the DP table based on previous results.
solution.py9 lines
1def numRollsToTarget(n, k, target):
2    MOD = 10**9 + 7
3    dp = [[0] * (target + 1) for _ in range(n + 1)]
4    dp[0][0] = 1
5    for i in range(1, n + 1):
6        for j in range(1, target + 1):
7            for face in range(1, min(k, j) + 1):
8                dp[i][j] = (dp[i][j] + dp[i - 1][j - face]) % MOD
9    return dp[n][target]

Complexity note: The time complexity is O(n * target * k) because we fill a table of size n x target and for each cell, we may iterate up to k times. The space complexity is O(n * target) for the DP table.

  • 1Dynamic programming allows us to break down the problem into smaller subproblems, making it more manageable.
  • 2Understanding the base cases and how to build upon them is crucial in dynamic programming.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.