Java实现-骰子求和

扔 n 个骰子,向上面的数字之和为 S。给定 Given n,请列出所有可能的 S 值及其相应的概率。

 注意事项

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

样例

给定 n = 1,返回 [ [1, 0.17], [2, 0.17], [3, 0.17], [4, 0.17], [5, 0.17], [6, 0.17]]

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];
		dp[1][1]=1;
		dp[1][2]=1;
		dp[1][3]=1;
		dp[1][4]=1;
		dp[1][5]=1;
		dp[1][6]=1;
		for(int i=2;i<=n;i++){
			for(int j=i;j<=i*6;j++){
				long x1=0,x2=0,x3=0,x4=0,x5=0,x6=0;
				if(j-1>0){
					x1=dp[i-1][j-1];
				}
				if(j-2>0){
					x2=dp[i-1][j-2];
				}
				if(j-3>0){
					x3=dp[i-1][j-3];
				}
				if(j-4>0){
					x4=dp[i-1][j-4];
				}
				if(j-5>0){
					x5=dp[i-1][j-5];
				}
				if(j-6>0){
					x6=dp[i-1][j-6];
				}
				dp[i][j]=x1+x2+x3+x4+x5+x6;
			}
		}
		List<Map.Entry<Integer, Double>> result=new ArrayList<Map.Entry<Integer,Double>>();
		for(int i=n;i<=6*n;i++){
			AbstractMap.SimpleEntry<Integer, Double> entry=new AbstractMap.SimpleEntry<Integer, Double>(i, dp[n][i]/Math.pow(6, n));
			result.add(entry);
		}
		return result;
    }
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Narasimha_Karumanchi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值