博客
关于我
动态规划——丑数、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/

    你可能感兴趣的文章
    None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
    查看>>
    NoNodeAvailableException None of the configured nodes are available异常
    查看>>
    Vue.js 学习总结(16)—— 为什么 :deep、/deep/、>>> 样式能穿透到子组件
    查看>>
    nopcommerce商城系统--文档整理
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>