【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。
注意:本题与主站 264 题相同:https://leetcode-cn.com/problems/ugly-number-ii/

方案:动态规划

相似题见:

264. 丑数 II

313. 超级丑数

1201. 丑数 III

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp = [1] * n 

        dp2, dp3, dp5 = 0, 0, 0

        for i in range(1, n):
            dp[i] = min(dp[dp2]*2, dp[dp3]*3, dp[dp5]*5)

            if dp[i] == dp[dp2] * 2:
                dp2 += 1
            if dp[i] == dp[dp3] * 3:
                dp3 += 1
            if dp[i] == dp[dp5] * 5:
                dp5 += 1

        return dp[-1]
发布了39 篇原创文章 · 获赞 12 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/wdh315172/article/details/105408601