【leetcode】1230.Toss Strange Coins
2024-09-05 18:13:34
题目如下:
You have some coins. The
i
-th coin has a probabilityprob[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.40000Example 2:
Input: prob = [0.5,0.5,0.5,0.5,0.5], target = 0
Output: 0.03125Constraints:
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]
最新文章
- SpringMVC接收页面表单参数
- 怎样实现ZBrush中的智能对称
- linux命令--dig
- java.util.Properties类
- JSONP解决ajax跨域问题
- 【Spring-AOP-学习笔记-7】@Around增强处理简单示例
- Ngix 移动端与Pc端 反向代理判断
- java对图片的裁剪(包括来自网络的图片)
- 1.3.4 try-with-resources (TWR)
- [Swust OJ 191]--迷宫逃离(打表搜索)
- Redis和nosql简介,api调用;Redis数据功能(String类型的数据处理);List数据结构(及Java调用处理);Hash数据结构;Set数据结构功能;sortedSet(有序集合)数
- DIV正确打开方式 ~~~~哈哈哈
- Java学习笔记(二)——类和对象
- Codeforces Round #546 (Div. 2)
- Spring Cloud Eureka简介及原理
- CSS3-flex弹性布局之flex属性
- Flex外包公司——案例汇总
- JAVA字符串类
- (转)mysql升级5.5.20时遇到的问题:1548-Cannot load from mysql.proc. The table is probably corrupted
- python学习之内存机制