Topic
给你一个整数 n ,请你找出并返回第 n 个 丑数 。
丑数 就是只包含质因数 2、3 和/或 5 的正整数。
Example_1
输入:n = 10
输出:12
解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是由前 10 个丑数组成的序列。
Example_2
输入:n = 1
输出:1
解释:1 通常被视为丑数。
Tips
1 <= n <= 1690
Solution
由于因数仅有2,3 和\或 5组成
那么不难看出 1 后面的丑数均有已有丑数得出
就可以利用动态规划解决本问题:
首先定义 3 个指针 index_2, index_3, index_5
分别用来表示丑数集合中还没乘过 2,3,5 的丑数位置。
之后每次新的丑数 dp[i] = min(dp[index2] * 2, dp[index3] * 3, dp[index5] * 5) 。
为了避免不同顺序的相同质因数相乘得到结果
则可以利用 dp[i] 是由 index2, index3, index5 中的哪个相乘得到的
对应的把此 index + 1
标记还没乘过该 index 的最小丑数变大了
Code
class Solution:
def nthUglyNumber(self, n: int) -> int:
ans = [0] * (n+1)
ans[1] = 1
index_2 = index_3 = index_5 = 1
index = 2
while index <= n:
a,b,c = ans[index_2] *2,ans[index_3]*3,ans[index_5]*5
m = min(a,b,c)
if m == a:
index_2 += 1
if m == b:
index_3 += 1
if m == c:
index_5 += 1
ans[index] = m
index += 1
return ans[n]