剑指offer-74、n个骰⼦的点数
题目描述把 n 个骰⼦扔在地上,所有骰⼦朝上⼀⾯的点数之和为 s 。输⼊ n ,打印出 s 的所有可能的值出现的概率。
你需要⽤⼀个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰⼦所能掷出的点数集合中第 i ⼩的那个的概率。
示例1:
输⼊: 1
输出:
示例2
输⼊: 2
输出:
思路及解答
暴力递归
枚举所有骰子组合。递归计算每个骰子的点数,统计所有可能的和
public class Solution { public double[] dicesProbability(int n) { // 骰子点数范围:n到6n,共5n+1种可能 int[] counts = new int; // 递归统计所有可能的和 backtrack(n, 0, counts); // 计算概率 double total = Math.pow(6, n); double[] res = new double; for (int i = 0; i < counts.length; i++) { res = counts / total; } return res; } private void backtrack(int remain, int sum, int[] counts) { if (remain == 0) { counts++; // 统计和出现的次数 return; } // 当前骰子可以是1到6点 for (int i = 1; i 懂技术并乐意极积无私分享的人越来越少。珍惜 感谢分享,学习下。 感谢分享 热心回复! 过来提前占个楼 感谢分享,学习下。 很好很强大我过来先占个楼 待编辑 感谢分享
页:
[1]