Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
LeetCode:链接
剑指offer:剑指Offer_编程题33:丑数
这题竟然是动态规划思想????
要求第n
个丑数,思考一下,第n
个丑数是怎么来的?它一定是在第n
个丑数之前的n-1
个丑数中的一个,乘以2
、3
、5
得来的。现在的问题就是,如何从前n-1
个丑数中选出那个丑数来,然后又如何确定是乘以2
,还是3
或者是5呀
?
对乘以2而言,肯定存在某一个丑数T2,排在它之前的每一个丑数乘以2得到的结果都会小于已有最大的丑数,在它之后的每一个丑数乘以乘以2得到的结果都会太大。我们只需要记下这个丑数的位置,同时每次生成新的丑数的时候,去更新这个T2。对乘以3和5而言,也存在着同样的T3和T5。
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n < 7:
return n
number = [1,2,3,4,5,6]
t2, t3, t5 = 3, 2, 1
for i in range(6, n):
cur = min(number[t2]*2, number[t3]*3, number[t5]*5)
number.append(cur)
while number[t2]*2 <= number[-1]:
t2 += 1
while number[t3]*3 <= number[-1]:
t3 += 1
while number[t5]*5 <= number[-1]:
t5 += 1
return number[-1]