LintCode : Dices Sum 骰子求和

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

Example
Example 1:

Input: n = 1
Output: [[1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]]
Explanation: Throw a dice, the sum of the numbers facing up may be 1, 2, 3, 4, 5, 6, and the probability of each result is 0.17.
Notice
You do not care about the accuracy of the result, we will help you to output results.
代码:
有三个未知数:扔骰子次数,在当前次数上和的取值范围,当前次扔骰子可能出现的点数。

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
        long[][] dp = new long[n+1][6*n+1];
        for(int i=1; i<=6; i++){
            dp[1][i] = 1;
        }
        
        for(int i=2; i<=n; i++){
            for(int j=i; j<=6*i; j++){
                for(int k=1; k<=6&&k<=j; k++){
                    dp[i][j] = dp[i][j] + dp[i-1][j-k];
                }
            }
        }
        
        double total = Math.pow(6,n);
        HashMap map = new HashMap<Integer,Double>();
        for(int i=n; i<=6*n; i++){
            map.put(i,dp[n][i]/total);
        }
        
        return new ArrayList<Map.Entry<Integer,Double>>(map.entrySet());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值