题目
我们把只包含质因子 2、3 和 5 的数称作丑数(Ugly Number)。求按从小到大的顺序的第 n 个丑数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
是前 10 个丑数。
说明:
- 1 是丑数。
-
方案
class Solution: def nthUglyNumber(self, n: int) -> int: # dp[i] 表示 第 i 个丑数 dp = [1] a, b, c = 0, 0, 0 for _ in range(1, n): _min = min(dp[a] * 2, dp[b] * 3, dp[c] * 5) dp.append(_min) if dp[a] * 2 == _min: a += 1 if dp[b] * 3 == _min: b += 1 if dp[c] * 5 == _min: c += 1 return dp[-1]
状态定义:
dp[n]
表示第 n 个丑数,a 表示 2 倍数字的索引用于dp[a]*2
,b 表示 3 倍数字的索引用于dp[b]*3
,c 表示 5 倍数字的索引用于dp[c]*5
- 转移方程:
**dp[n] = min(dp[a]*2, dp[b]*3, dp[c]*5)**
- 每次计算之后,如果 2 倍的数字最小,则 a++,如果 3 倍的数字最小,则 b++,如果 5 倍的数字最小,则 c++
- 初始状态:
dp[0]=1
,因为第一个丑数是 1原文
https://leetcode-cn.com/leetbook/read/illustrate-lcof/50qoxc/