美文网首页
LC contest 149 (记录ing

LC contest 149 (记录ing

作者: shirleyhou | 来源:发表于2019-08-11 23:31 被阅读0次

比较难过的就是第二题, 明明做对了, 但是因为非常智障的问题一直没过.
第二题链接: https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/

先是一个非常智障的问题: 我以为10^9Math.pow(10,9)...翻来覆去的改了半个小时.
然后因为long的overflow问题, 一直没有debug出来.因为每一步存储的时候都需要注意overflow! 所以每次在+, +=的时候注意都需要mod (10^9+7)

自己想的DFS解法

class Solution {
    HashMap<String, Long> memo;
    int MOD = 1000000000+7;
    public int numRollsToTarget(int d, int f, int target) {
        memo = new HashMap<>();
        long res = helper(d, f, target);
        System.out.println(res);
        return (int)res%((int)(Math.pow(10,9)+7));
    }
    public long helper(int d, int f, int target){
        
        if (d==0 && target==0) return 1;
        else if (target<0||(target>f && d==1)||d<0) return 0;
        
        String key = Integer.toString(d)+" "+Integer.toString(target);
        if (memo.containsKey(key)) return memo.get(key);
        
        long res= 0;
        for(int i = 1;i<=f;i++){
            res = (res + (helper(d - 1, f, target - i) % MOD)) % MOD;
        }
        memo.put(key, res);
        return res;
    }
}

动态规划解法: 参考GFG的做法或者参考roll dice (LintCode20 算dice概率那题的简化版本)

class Solution {
    int MOD = 1000000000+7;
    public int numRollsToTarget(int d, int f, int target) {
        int [][]dp=new int[d+1][f*d+1];
        if (target>f*d) return 0;
        for(int i = 1;i<=f;i++){
            dp[1][i] = 1;
        }
        for(int i=2;i<=d;i++){
            for(int j=i;j<=i*f;j++){
                int temp = 0;
                for(int k=1;k<=f;k++){
                    if(j-k>=0){
                        temp= (temp+(dp[i-1][j-k])%MOD)%MOD;
                    }
                }
                dp[i][j]=temp;
            }
        }
        return dp[d][target] % MOD;
    }
}

相关文章

  • LC contest 149 (记录ing

    比较难过的就是第二题, 明明做对了, 但是因为非常智障的问题一直没过.第二题链接: https://leetcod...

  • LC吐血整理之-weekly_contest

    12.29开始做周赛! 169场周赛 5296.两棵二叉搜索树中的所有元素 我的做法:遍历两棵二叉搜索树得到两个数...

  • 记录ing

    记录最初运动的时间,那时候只是单纯的想瘦,14年八月,经过一个月的努力的确瘦了十斤,那一个月几乎每周有五天在打卡,...

  • LeetCode前两百刷题(1~20)

    leetcode lc1 & lc15& lc 16 & lc 18 多数之和问题 https://www.jia...

  • 梦境记录149

    昨天梦见在家里看以前的碟片,然后还很害怕看见以前家里的恐怖片d(ŐдŐ๑)后来爸妈敲门进来了,我就准备跟着他们出去...

  • 副业记录149

    知乎等级还差70分就能冲刺等级4了,加油^0^~,明天休息一天,要去打疫苗了,早上就去,下午能好好休息一下的。晚上...

  • 学习ing记录

    一、去除掉EdiitText底部下划线,background=“@null”即可 二、实现倒计时效果 caseR....

  • DP真题

    骨骼清奇:LC 62LC 337 House Robber III LC 486 Predict the Win...

  • 739. Daily Temperatures

    https://leetcode.com/contest/weekly-contest-61/problems/d...

  • 696. Count Binary Substrings

    https://leetcode.com/contest/leetcode-weekly-contest-54/p...

网友评论

      本文标题:LC contest 149 (记录ing

      本文链接:https://www.haomeiwen.com/subject/hjpejctx.html