Lintcode20 Dices Sum solution 题解
来源:互联网 发布:seo从入门到精通 编辑:程序博客网 时间:2024/06/05 21:00
【题目描述】
Throw n dices, the sum of the dices' faces is S. Given n, find the all possible value of S along with its probability.
Notice:You do not care about the accuracy of the result, we will help you to output results.
扔 n 个骰子,向上面的数字之和为 S。给定 Given n,请列出所有可能的 S 值及其相应的概率。
注意:你不用关注答案的准确性,我们会帮你输出答案
【题目链接】
http://www.lintcode.com/en/problem/dices-sum/
【题目解析】
这题用dfs做感觉更加直观,但是过不了time cost。换成dp的方法我是这么想的:
用dp[i][j]表示有i + 1个骰子的情况下,掷到的和为j的次数。那么intialize这个dp[0][j], j = 1...6的值都为1,然后从i = 1开始做循环。i个骰子和i + 1个骰子的差别就是1个骰子(废话),所以再用一个k = 1...6进行遍历,那么i + 1个骰子掷到j + k的次数就是原来dp[i][j + k]的次数加上dp[i - 1][j]。
这样我们就求得了n个骰子的情况下,每个S出现的次数dp[n - 1][j], j = n...6 * n。那么概率就是每个dp[n - 1][j]除以出现的总次数sum(dp[n - 1][j]).
这里要注意dp的值可能很大,所以要用到long long,否则在有些test case(e.g., n = 15)的情况下,会出现负数答案。
【答案链接】
http://www.jiuzhang.com/solution/dices-sum/
- Lintcode20 Dices Sum solution 题解
- #20 Dices Sum
- [LintCode]Dices Sum
- lintcode: Dices Sum
- Lintcode56 Two Sum solution 题解
- Lintcode57 3Sum solution 题解
- Lintcode58 4Sum solution 题解
- Lintcode89 K Sum solution 题解
- Lintcode90 K Sum || solution 题解
- Lintcode135 Combination Sum solution 题解
- Lintcode138 Subarray Sum solution 题解
- Lintcode59 3Sum Closest solution 题解
- Lintcode110 Minimum Path Sum solution 题解
- Lintcode139 Subarray Sum Closest solution 题解
- Lintcode153 Combination Sum II solution 题解
- Lintcode94 Binary Tree Maximum Path Sum solution 题解
- Lintcode13 strStr solution 题解
- Lintcode15 Permutations solution 题解
- 安装 Kali Linux 后需要做的 20 件事
- Dubbo原理简单分析
- 用python脚本实现自动部署环境(二)
- 空格键展示animate.css 动画效果
- 服务器开发大纲
- Lintcode20 Dices Sum solution 题解
- log4j.xml配置文件demo
- mmap函数
- linux系统定时任务(cron服务)设置
- html:简单布局
- 设置mysql密码
- 自定义圆形经验统计View
- VUE 新手环境搭建-发布
- Linux下C测试const