博客
关于我
动态规划——丑数、n个骰子的点数
阅读量:345 次
发布时间:2019-03-04

本文共 1205 字,大约阅读时间需要 4 分钟。

1. 丑数

丑数(Ugly Number)是指只包含质因数2、3和5的数。生成丑数的方法可以通过动态规划来实现。每个丑数可以看作是前一个丑数乘以2、3或5的结果。为了找到第n个丑数,我们可以使用以下方法:

def nthUglyNumber(n):    if n == 0:        return 0    dp = [1]  # dp[0] = 1    for _ in range(n):        next_dp = []        for num in dp:            for factor in [2, 3, 5]:                next_dp.append(num * factor)        dp = list(set(next_dp))  # 去重        dp.sort()  # 保持有序    return dp[n-1]

2. n个骰子的点数概率

为了计算n个骰子点数和的概率,我们可以使用动态规划的方法。每个骰子有6个可能的点数,我们需要计算所有可能的点数和及其对应的概率。

def dicesProbability(n):    if n == 0:        return []    # 初始化一个一维数组来保存当前骰子的概率分布    dp = [1.0 / 6.0] * (n * 6 + 1)    for i in range(1, n + 1):        # 创建一个新的数组来保存i个骰子的概率分布        new_dp = [0.0] * (6 * i + 1)        for j in range(1, 6 + 1):            for k in range(i):                new_dp[i + j] += dp[k] * (1.0 / 6.0)        dp = new_dp    # 计算每个可能的点数和的概率    max_sum = 6 * n    min_sum = n    result = [0.0] * (max_sum - min_sum + 1)    for s in range(min_sum, max_sum + 1):        result[s - min_sum] = dp[s]    return result

结果展示

  • 丑数:通过上述方法,可以高效地找到第n个丑数。例如,第1个丑数是1,第2个是2,第3个是4,依此类推。
  • 骰子概率:通过动态规划,可以计算出n个骰子点数和的所有可能值及其概率分布。例如,n=2时,点数和的概率分布为:2: 1/6, 3: 2/6, 4: 3/6, 5: 4/6, 6: 5/6, 7: 6/6。
  • 以上方法保证了代码的高效性和正确性,适用于不同的n值。

    转载地址:http://wese.baihongyu.com/

    你可能感兴趣的文章
    Prometheus 采集器使用详解
    查看>>
    Prometheus 黑盒监控实战
    查看>>
    prometheus+alertmanager+grafana监控部署教程
    查看>>
    Prometheus+Grafana构建智能化Kubernetes监控系统实战
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    prometheus安装
    查看>>
    Prometheus实战教程:监控Kafka消息
    查看>>
    Prometheus实战教程:监控mysql数据库
    查看>>
    Prometheus实战教程:监控Nginx状态
    查看>>
    prometheus常用exporter下载地址大全
    查看>>
    Prometheus快速搭建与监控Linux系统实战
    查看>>
    prometheus报警与恢复告警的格式
    查看>>
    Pytorch中安装 torch_geometric 详细图文操作(全)
    查看>>
    prometheus监控docker容器实战
    查看>>
    Prometheus监控k8s集群使用邮箱和微信告警!
    查看>>
    Prometheus监控mysq数据库实战
    查看>>
    prometheus监控nginx实战
    查看>>
    Prometheus监控redis数据库实战
    查看>>
    Prometheus监控教程:使用Grafana展示主机基本信息
    查看>>