题目如下:

You have some coins.  The i-th coin has a probability prob[i] of facing heads when tossed.

Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.

Example 1:

Input: prob = [0.4], target = 1
Output: 0.40000

Example 2:

Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125

Constraints:

  • 1 <= prob.length <= 1000
  • 0 <= prob[i] <= 1
  • 0 <= target <= prob.length
  • Answers will be accepted as correct if they are within 10^-5 of the correct answer.

解题思路:动态规划。首先假设dp[i][j]为投完第i枚硬币后有j枚硬币朝上的概率。如果第i-1枚硬币投完后有j枚朝上,那么第i枚硬币就只能朝下;如果i-1枚硬币投完后有j-1枚朝上,那么第i枚硬币就只能朝上。很容易建立状态转移方程,dp[i][j] = dp[i-1][j-1] * prob[i] + dp[i-1][j] * (1 - prob[i])。

代码如下:

class Solution(object):
def probabilityOfHeads(self, prob, target):
"""
:type prob: List[float]
:type target: int
:rtype: float
"""
dp = [[0]*(len(prob) + 1) for _ in prob] dp[0][0] = 1 - prob[0]
dp[0][1] = prob[0] for i in range(1,len(prob)):
for j in range(min(target+1,len(prob))):
if j == 0:
dp[i][j] = float(dp[i-1][j]) * (1 - prob[i])
continue
dp[i][j] = float(dp[i-1][j-1]) * prob[i] + float(dp[i-1][j]) * (1 - prob[i])
return dp[-1][target]

最新文章

  1. SpringMVC接收页面表单参数
  2. 怎样实现ZBrush中的智能对称
  3. linux命令--dig
  4. java.util.Properties类
  5. JSONP解决ajax跨域问题
  6. 【Spring-AOP-学习笔记-7】@Around增强处理简单示例
  7. Ngix 移动端与Pc端 反向代理判断
  8. java对图片的裁剪(包括来自网络的图片)
  9. 1.3.4 try-with-resources (TWR)
  10. [Swust OJ 191]--迷宫逃离(打表搜索)
  11. Redis和nosql简介,api调用;Redis数据功能(String类型的数据处理);List数据结构(及Java调用处理);Hash数据结构;Set数据结构功能;sortedSet(有序集合)数
  12. DIV正确打开方式 ~~~~哈哈哈
  13. Java学习笔记(二)——类和对象
  14. Codeforces Round #546 (Div. 2)
  15. Spring Cloud Eureka简介及原理
  16. CSS3-flex弹性布局之flex属性
  17. Flex外包公司——案例汇总
  18. JAVA字符串类
  19. (转)mysql升级5.5.20时遇到的问题:1548-Cannot load from mysql.proc. The table is probably corrupted
  20. python学习之内存机制

热门文章

  1. neutron网络服务
  2. 重新网格化(Remesh)
  3. 问题记录 | 记录PIL中Image.save的一个坑
  4. JS 截取字符的方法
  5. idea运行时 Process finished with exit code -1073741819 (0xC0000005)
  6. 使用批处理选择运行控制台程序(简易cui)
  7. python 9*9乘法口诀 猜数字游戏
  8. 如何用item pipeline(管道)清洗数据
  9. 剑指offer 剪绳子
  10. mysql数据库基础命令(一)