我们把只包含因子 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/
方案:动态规划
相似题见:
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]