题目描述
编写一个程序,找出第 n 个丑数。
丑数就是质因数只包含 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
思路
首先我们可以很容易想到递归求解,但是递归求解有一个问题,那就是存在大量重复运算,因此时间复杂度高,在LeetCode上超出时间限制。但是递归的思路可以用来求解LeetCode263.丑数并且在LeetCode上提交通过。
如果用递归求解本道题,代码可以参考如下:
代码待补充
动态规划求解
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
nums = [1]
i2 = i3= i5 = 0
for _ in range(n-1):
ugly = min(nums[i2]*2,nums[i3]*3,nums[i5]*5)
nums.append(ugly)
while nums[i2] * 2 <= ugly:
i2+=1
while nums[i3] * 3 <= ugly:
i3+=1
while nums[i5] * 5 <= ugly:
i5+=1
return nums[-1]
思路是,每次只拿遍历数里面与2,3,5相乘最小的那个,放到数组里,该i的指针+1