我们把只包含因子 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]