LeetCode 1155 Number of Dice Rolls With Target Sum (dp 分组背包)

244 篇文章 0 订阅
177 篇文章 0 订阅

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

题目链接:https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/

题目分析:裸的分组背包,一共d个筛子即d组,每组必须且只能选出一个数字,dp[i][j]表示用到第i个筛子,组成数字j的方案数

15ms,时间击败53%

class Solution {
    
    public final int MOD = 1000000007;
    
    public int numRollsToTarget(int d, int f, int target) {
        int[][] dp = new int[d + 1][target + 1];
        for (int i = 1; i <= Math.min(f, target); i++) {
            dp[1][i] = 1;
        }
        for (int i = 2; i <= d; i++) {
            for (int j = 1; j <= target; j++) {
                for (int k = 1; k <= f && k < j; k++) {
                    dp[i][j] = (dp[i][j] + dp[i - 1][j - k]) % MOD;
                }
            }
        }
        return dp[d][target];
    }
}

空间可以优化,同时可以加一些特判,此处第二层循环逆序的原因同0/1背包

4ms,时间击败96.21%

class Solution {
    
    public final int MOD = 1000000007;
    
    public int numRollsToTarget(int d, int f, int target) {
        int m = d * f;
        if (target < d || m < target) {
            return 0;
        }
        int[] dp = new int[target + 1];
        for (int i = 1; i <= Math.min(f, target); i++) {
            dp[i] = 1;
        }
        for (int i = 2; i <= d; i++) {
            for (int j = target; j >= 1; j--) {
                dp[j] = 0;
                for (int k = 1; k <= f && k < j; k++) {
                    dp[j] = (dp[j] + dp[j - k]) % MOD;
                }
            }
        }
        return dp[target];
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值