1. 程式人生 > >lintcode 20 Dices Sum

lintcode 20 Dices Sum

題目描述

Description
Throw n dices, the sum of the dices’ faces is S. Given n, find the all possible value of S along with its probability.

  • You do not care about the accuracy of the result, we will help you to output results.

Example
Given n = 1, return [ [1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]].

思路

看到這題,首先想到的就是動態規劃了,二維陣列記錄概率,然後用公式來求解:在這裡插入圖片描述
n是骰子數量,a是點數,f(n,a)指的是n個骰子點數為a的概率
有了公式就很方便進行求解了

  • 第一層迴圈,表示骰子數量
  • 第二層迴圈,表示點數
  • 第三層迴圈,用來計算概率

程式碼

public List<Map.Entry<Integer, Double>> dicesSum(int n) {
        // Write your code here
        // Ps. new AbstractMap.SimpleEntry<Integer, Double>(sum, pro)
// to create the pair List<Map.Entry<Integer, Double>> result = new ArrayList<>(); double[][] dp = new double[n + 1][n * 6 + 1]; for (int i = 1; i < 7; i++) { dp[1][i] = 1.0 / 6; } for (int i = 2; i <= n; i++) { for
(int j = i; j <= 6 * i; j++) { for (int m = 1; m <= 6; m++) { if (j > m) { dp[i][j] += dp[i - 1][j - m]; } } dp[i][j] /= 6.0; } } for (int i = n; i <= 6 * n; ++i) { result.add(new AbstractMap.SimpleEntry<>(i, dp[n][i])); } return result; }