(python)小菜狗算法日记(动态规划系列)_leetcode 面试题49. 丑数

我们把只包含因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。

示例:

输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:  

1 是丑数。
n 不超过1690。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/chou-shu-lcof
思路:想破头颅都想不到的非典型动态规划。设a,b,c三个指针,dp[i]的值是dp[a]*2,dp[b]*3,dp[c]*5中最小的那个,这么神奇的方法是怎么想到的嗷。

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp = [0]*(n)
        dp[0]=1
        a,b,c = 0,0,0
        for i in range(1,n):
            dp[i]=min(dp[a]*2,dp[b]*3,dp[c]*5)
            if dp[i]==dp[a]*2: #三个都是if,因为如果dp[a]*2==dp[b]*3时,a,b都得加一
                a+=1
            if dp[i]==dp[b]*3:
                b+=1
            if dp[i]==dp[c]*5:
                c+=1
        return dp[-1]

大佬代码:作者:jyd 链接:https://leetcode-cn.com/problems/chou-shu-lcof/solution/mian-shi-ti-49-chou-shu-dong-tai-gui-hua-qing-xi-t/ 来源:力扣(LeetCode)

class Solution:
    def nthUglyNumber(self, n: int) -> int: 
       dp, a, b, c = [1] * n, 0, 0, 0
        for i in range(1, n):
            n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5
            dp[i] = min(n2, n3, n5)
            if dp[i] == n2: a += 1
            if dp[i] == n3: b += 1
            if dp[i] == n5: c += 1
        return dp[-1]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值