把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。
你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nge-tou-zi-de-dian-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.stream.IntStream;
class Solution {
public double[] dicesProbability(int n) {
if (n <= 0) {
return new double[0];
}
TreeMap<Integer, Double> probability = new TreeMap<Integer, Double>() {{
IntStream.range(1, 7).forEach(k -> put(k, 1 / 6.0));
}};
TreeMap<Integer, Double> dp = new TreeMap<Integer, Double>() {{
put(0, 1D);
}};
for (int i = 1; i <= n; ++i) {
TreeMap<Integer, Double> helper = new TreeMap<>();
for (Map.Entry<Integer, Double> entry1 : dp.entrySet()) {
for (Map.Entry<Integer, Double> entry2 : probability.entrySet()) {
int key = entry1.getKey() + entry2.getKey();
double value = entry1.getValue() * entry2.getValue();
helper.put(key, helper.getOrDefault(key, 0D) + value);
}
}
dp = helper;
}
int index = 0;
double[] ans = new double[dp.size()];
for (Map.Entry<Integer, Double> entry : dp.entrySet()) {
ans[index++] = entry.getValue();
}
return ans;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
new Solution().dicesProbability(in.nextInt());
}
}
}