扔 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]]
。
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;
}
}
}