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

    你可能感兴趣的文章
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>