当前位置:网站首页>【剑指 Offer】 60. n个骰子的点数
【剑指 Offer】 60. n个骰子的点数
2022-07-06 10:11:00 【LuZhouShiLi】
剑指 Offer 60. n个骰子的点数
题目
把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概率。你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中第 i 小的那个的概率。
思路
- 首先用数组的第一维表示阶段,也就是投掷完几个骰子
- 然后用数组的第二维表示投掷完这些骰子之后,可能出现的点数
- 数组的值就表示,该阶段各个点数出现的次数
代码
class Solution {
public:
vector<double> dicesProbability(int n) {
int dp[12][70];
memset(dp,0,sizeof(dp));// 全部初始化0
for(int i = 1; i <= 6; i++)
{
dp[1][i] = 1;// 状态数组初始化
}
for(int i = 2; i <= n; i++)
{
// 最大点数 一定是 6 * i
for(int j = i; j <= 6 * i; j++)
{
for(int cur = 1; cur <= 6; cur++)
{
if(j - cur <= 0)
{
break;
}
// 但看第i个骰子,点数可能为1 2 3 4 5 6 因此点数j出现的次数是由投掷完第 i - 1个骰子 对应点数 j - 1 j - 2 j - 6 出现的次数之和转化过来的
dp[i][j] += dp[i - 1][j - cur];
}
}
}
int all = pow(6,n);// 所有可能性
vector<double> ret;
for(int i = n; i <= n * 6; i++)
{
ret.push_back(dp[n][i] * 1.0 / all);
}
return ret;
}
};
边栏推荐
猜你喜欢

传统家装有落差,VR全景家装让你体验新房落成效果

Pourquoi Li shufu a - t - il construit son téléphone portable?

推荐好用的后台管理脚手架,人人开源

IP, subnet mask, gateway, default gateway

There is a gap in traditional home decoration. VR panoramic home decoration allows you to experience the completion effect of your new house

Heavy! Ant open source trusted privacy computing framework "argot", flexible assembly of mainstream technologies, developer friendly layered design

Windows连接Linux上安装的Redis

中移动、蚂蚁、顺丰、兴盛优选技术专家,带你了解架构稳定性保障

模板于泛型编程之declval

面试突击63:MySQL 中如何去重?
随机推荐
Pytest learning ----- detailed explanation of the request for interface automation test
30 分钟看懂 PCA 主成分分析
Is it meaningful for 8-bit MCU to run RTOS?
node の SQLite
The latest financial report release + tmall 618 double top, Nike energy leads the next 50 years
高精度运算
编译原理——自上而下分析与递归下降分析构造(笔记)
Open source and safe "song of ice and fire"
Pourquoi Li shufu a - t - il construit son téléphone portable?
酷雷曼多种AI数字人形象,打造科技感VR虚拟展厅
Markdown grammar - better blogging
What is the reason why the video cannot be played normally after the easycvr access device turns on the audio?
Jerry's watch deletes the existing dial file [chapter]
[Android] kotlin code writing standardization document
二分(整数二分、实数二分)
Scratch epidemic isolation and nucleic acid detection Analog Electronics Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022
adb常用命令
Unity particle special effects series - treasure chest of shining stars
VR panoramic wedding helps couples record romantic and beautiful scenes
推荐好用的后台管理脚手架,人人开源