码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode20 Dices Sum solution 题解

时间:2017-04-30 22:51:20      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:solution   result   possible   about   

【题目描述】

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 题解

标签:solution   result   possible   about   

原文地址:http://12799252.blog.51cto.com/12789252/1920887

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!