Lintcode 20 骰子求和

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

样例

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

思路:扔n个骰子数字和及概率相当于求前n-1个骰子和及概率与第n个骰子和及概率。
1.当n<=0,返回空
2.当n=1时,返回1-6概率0.17;
3.当n>1时,递归调用返回List<map.entry>,对List的每一个骰子和
(Entry中的key)循环加1-6,作为新的key存到一个map中,
①当map中不包含这个key时,Map中插入概率等于1.0/6* value(value是Entry中的value)

②当map中包含这个key时,Map中插入概率等于之前的概率+1.0/6*value



代码如下:

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
        HashMap<Integer, Double> map = new HashMap<Integer, Double>();

        List<Map.Entry<Integer, Double>> list = null;


        
        if(n<=0){
           return null;
        }
        if(n ==1){
            for(int i =1;i<=6;i++){
            map.put(i,1.0/6);
            }
            
            list = new ArrayList<Map.Entry<Integer,Double>>(map.entrySet());
            
            return list;
        }else{
            list = dicesSum(n-1);
            System.out.println(list);
            int size = list.size();
            for(int i=0;i<size;i++){
                
                Map.Entry<Integer,Double> mapentry = list.get(i);
                
                Integer key = mapentry.getKey();
                Double value = mapentry.getValue();
                Integer tempkey =0;
                Double tempvalue = 0.0;
                for(int j=1;j<=6;j++){
                    tempkey = key+j;;
                    if(!map.containsKey(tempkey)){
                        tempvalue= value*(1.0/6);
                    }else{
                        tempvalue = value*1.0/6+map.get(tempkey);
                    }
                
                    map.put(tempkey,tempvalue);
                }
                
                
            }
            list = new ArrayList<Map.Entry<Integer,Double>>(map.entrySet());
            return list;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值