LeetCode 1155. Number of Dice Rolls With Target Sum

原题链接在这里:https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/

题目:

You have d dice, and each die has f faces numbered 1, 2, ..., f.

Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.

 

Example 1:

Input: d = 1, f = 6, target = 3
Output: 1
Explanation: 
You throw one die with 6 faces.  There is only one way to get a sum of 3.

Example 2:

Input: d = 2, f = 6, target = 7
Output: 6
Explanation: 
You throw two dice, each with 6 faces.  There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.

Example 3:

Input: d = 2, f = 5, target = 10
Output: 1
Explanation: 
You throw two dice, each with 5 faces.  There is only one way to get a sum of 10: 5+5.

Example 4:

Input: d = 1, f = 2, target = 3
Output: 0
Explanation: 
You throw one die with 2 faces.  There is no way to get a sum of 3.

Example 5:

Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation: 
The answer must be returned modulo 10^9 + 7.

Constraints:

  • 1 <= d, f <= 30
  • 1 <= target <= 1000

题解:

Let dp[k] denotes the way to make up target k.

For each dice, there could be value j within [1, f]. dp[k - j] is accumlated to new value.

New value need all the original values of dp, thus here we need a temp.

Time Complexity: O(d * f * target).

Space: O(target).

AC Java:

 1 class Solution {
 2     public int numRollsToTarget(int d, int f, int target) {
 3         int mod = 1000000007;
 4         int [] dp = new int[target + 1];
 5         dp[0] = 1;
 6         
 7         for(int i = 0; i < d; i++){
 8             int [] temp = new int[target + 1];
 9             for(int j = 1; j <= f; j++){
10                 for(int k = j; k <= target; k++){
11                     temp[k] = (temp[k] + dp[k - j]) % mod; 
12                 }
13             }
14             
15             dp = temp;
16         }
17         
18         return dp[target];
19     }
20 }

类似Coin Change 2.

你可能感兴趣的:(LeetCode 1155. Number of Dice Rolls With Target Sum)