【剑指offer系列】 n个骰子的点数___43
来源:互联网 发布:苹果笔记本mac游戏 编辑:程序博客网 时间:2024/05/16 18:22
题目描述:
把n个骰子仍在地上,所有骰子朝上一面的点数之和为S。
输入n,输出S的所有可能值的出现概率
示例:
输入:n = 1
输出:S可能为1~6,每个出现的概率相等,均为0.166666
分析:
如果基于递归,可能会有很多重复的操作,因此采用循环来实现。
对于n个骰子,可能6^n种情况。首先统计每个值出现的次数,然后除以6^n即为每种情况可能的概率
从1个骰子开始,循环计算直到计算出所有n个骰子所有可能的情况。
对于k个骰子,k-1个骰子的所有情况已经计算出来,因此k个骰子在k-1的基础上对每个值加1 2 3 4 5 6即为k个骰子所有可能的情况
代码:
void probability(int num){ if(n<1) return; vector<vector<int> > sum(2,vector<int>(6*num+1,0)); int flag=0; for(int i=1;i<=6;++i){ sum[flag][i]=1; } for(int k=2;k<=num;++k){ for(int i=0;i<k;++i){ sum[1-flag][i]=0; } for(int i=k;i<=6*k;++i){ sum[1-flag][i]=0; for(int j=1;j<=i&&j<=6;++j){ sum[1-flag][i]+=sum[flag][i-j]; } } flag=1-flag; } double total=(double)pow(6,num); for(int i=num;i<=6*num;++i){ double ratio=(double)sum[flag][i]/total; cout<<ratio<<endl; }}
0 0
- 【剑指offer系列】 n个骰子的点数___43
- 剑指offer面试题43 n个骰子的点数
- 【剑指offer】面试题43:n个骰子的点数
- 剑指Offer:面试题43 n个骰子的点数
- 剑指Offer之 - n个骰子的点数
- 剑指offer 43-n个骰子的点数
- 面试题43:n个骰子的点数(《剑指offer》)
- 剑指offer-面试题43:n个骰子的点数
- 【剑指offer-Java版】43n个骰子的点数
- 剑指offer(47):n个骰子的点数
- 《剑指offer》:[43]N个骰子的点数
- 剑指offer面试题43:n个骰子的点数
- 《剑指offer》43:n个骰子的点数
- 剑指offer:n个骰子的点数(java)
- 剑指offer-面试题43-n个骰子的点数
- 剑指offer 43. n个骰子的点数
- 剑指offer 面试题43 n个骰子的点数
- 剑指Offer——n个骰子的点数
- elgg安装
- 策略模式
- Spring+Struts2+Mybatis
- 大数据相关技术
- 利用check_mysql_health监控mysql数据
- 【剑指offer系列】 n个骰子的点数___43
- Javascript异步编程的4种方法
- [LintCode] 跳跃游戏II Jump Game II
- SqlServer发送邮件
- 判断ftp是否登录成功
- Youshua Bengio等人新书《Deep Learning》评介
- iOS学习笔记06-手势识别
- iOS 离屏渲染的研究(二)
- ios tableView去掉多余分割线 和最后一行分割线顶头显示