【題目描述】
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/