新聞中心
【題目描述】
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 個骰子,向上面的數(shù)字之和為 S。給定 Given n,請列出所有可能的 S 值及其相應(yīng)的概率。
注意:你不用關(guān)注答案的準(zhǔn)確性,我們會幫你輸出答案
【題目鏈接】
http://www.lintcode.com/en/problem/dices-sum/
【題目解析】
這題用dfs做感覺更加直觀,但是過不了time cost。換成dp的方法我是這么想的:
用dp[i][j]表示有i + 1個骰子的情況下,擲到的和為j的次數(shù)。那么intialize這個dp[0][j], j = 1...6的值都為1,然后從i = 1開始做循環(huán)。i個骰子和i + 1個骰子的差別就是1個骰子(廢話),所以再用一個k = 1...6進(jìn)行遍歷,那么i + 1個骰子擲到j(luò) + k的次數(shù)就是原來dp[i][j + k]的次數(shù)加上dp[i - 1][j]。
這樣我們就求得了n個骰子的情況下,每個S出現(xiàn)的次數(shù)dp[n - 1][j], j = n...6 * n。那么概率就是每個dp[n - 1][j]除以出現(xiàn)的總次數(shù)sum(dp[n - 1][j]).
這里要注意dp的值可能很大,所以要用到long long,否則在有些test case(e.g., n = 15)的情況下,會出現(xiàn)負(fù)數(shù)答案。
【答案鏈接】
http://www.jiuzhang.com/solution/dices-sum/
本文標(biāo)題:Lintcode20DicesSumsolution題解-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://www.dlmjj.cn/article/ephsc.html