http://www.lintcode.com/en/problem/dices-sum/
骰子投掷n次,求所有情况的和出现的概率
二维数组dp[i][j]保存投掷i次得到和为j的概率,当前位置的概率为当前投掷1 ~ 6的情况下的前序概率和
public class Solution {
/**
* @param n an integer
* @return a list of Map.Entry<sum, probability>
*/
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>> res = new LinkedList();
double[][] dp = new double[n + 1][6 * n + 1];
for (int i = 1; i <= 6; i++) {
dp[1][i] = 1.0 / 6.0;
}
for (int i = 2; i <= n; i++) {
for (int j = i; j <= 6 * i; j++) {
for (int k = 1; k <= 6; k++) {
if (j > k) {
dp[i][j] += dp[i - 1][j - k];
}
}
dp[i][j] /= 6.0;
}
}
for (int i = n; i <= 6 * n; i++) {
res.add(new AbstractMap.SimpleEntry<Integer, Double>(i, dp[n][i]));
}
return res;
}
}