LeetCode solutions

1263. Number of Dice Rolls With Target Sum

My accepted Python solution to LeetCode problem 1263, Number of Dice Rolls With Target Sum, running in 465ms.

  • Difficulty: Medium
  • Python
  • Runtime 465ms
  • Memory 17.9MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 465ms, memory 17.9MB, accepted 2026-01-02.

python
class Solution:
    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        MOD = 10**9 + 7
        
        # dp[i][j] = number of ways to get sum j using i dice
        dp = [[0] * (target + 1) for _ in range(n + 1)]
        dp[0][0] = 1
        
        for i in range(1, n + 1):
            for j in range(1, target + 1):
                for face in range(1, k + 1):
                    if j >= face:
                        dp[i][j] = (dp[i][j] + dp[i - 1][j - face]) % MOD
        
        return dp[n][target]

Source