Skip to content

Latest commit

 

History

History
144 lines (111 loc) · 3.29 KB

File metadata and controls

144 lines (111 loc) · 3.29 KB

English Version

题目描述

有一些不规则的硬币。在这些硬币中,prob[i] 表示第 i 枚硬币正面朝上的概率。

请对每一枚硬币抛掷 一次,然后返回正面朝上的硬币数等于 target 的概率。

 

示例 1:

输入:prob = [0.4], target = 1
输出:0.40000

示例 2:

输入:prob = [0.5,0.5,0.5,0.5,0.5], target = 0
输出:0.03125

 

提示:

  • 1 <= prob.length <= 1000
  • 0 <= prob[i] <= 1
  • 0 <= target <= prob.length
  • 如果答案与标准答案的误差在 10^-5 内,则被视为正确答案。

解法

0-1 背包问题。

Python3

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

空间优化:

class Solution:
    def probabilityOfHeads(self, prob: List[float], target: int) -> float:
        dp = [0] * (target + 1)
        dp[0] = 1
        for v in prob:
            for j in range(target, -1, -1):
                dp[j] *= (1 - v)
                if j >= 1:
                    dp[j] += dp[j - 1] * v
        return dp[-1]

Java

class Solution {
    public double probabilityOfHeads(double[] prob, int target) {
        double[] dp = new double[target + 1];
        dp[0] = 1;
        for (double v : prob) {
            for (int j = target; j >= 0; --j) {
                dp[j] *= (1 - v);
                if (j >= 1) {
                    dp[j] += dp[j - 1] * v;
                }
            }
        }
        return dp[target];
    }
}

C++

class Solution {
public:
    double probabilityOfHeads(vector<double>& prob, int target) {
        vector<double> dp(target + 1);
        dp[0] = 1;
        for (auto v : prob) {
            for (int j = target; j >= 0; --j) {
                dp[j] *= (1 - v);
                if (j >= 1) dp[j] += dp[j - 1] * v;
            }
        }
        return dp[target];
    }
};

Go

func probabilityOfHeads(prob []float64, target int) float64 {
	dp := make([]float64, target+1)
	dp[0] = 1
	for _, v := range prob {
		for j := target; j >= 0; j-- {
			dp[j] *= (1 - v)
			if j >= 1 {
				dp[j] += dp[j-1] * v
			}
		}
	}
	return dp[target]
}

...