At first glance, I knew that it was a dp problem, but I couldn't figure out the idea. The core and difficulty of the dp problem is to abstract the relationship function between the final optimal solution and the sub-optimal solution. In this question, you need to use opt[n-1]…opt[1] to find opt[n], but each number from 1 to n-1 has *2, *3, and 5 as opt[n] The possible solution is too complicated. It is very enlightening to understand the idea of the question. You only need to start with the first number 1, and use three indexes to control the position of the number 2, *3, *5. The next ugly number is the smallest value corresponding to the three indexes, and then move the corresponding index one place to the right, looping this strategy:
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
ind_2, ind_3, ind_5 = 0, 0, 0
ugly = n*[1]
for i in range(1,n):
ugly[i] = min(ugly[ind_2]*2, ugly[ind_3]*3, ugly[ind_5]*5)
if ugly[i] == ugly[ind_2]*2: ind_2+=1
if ugly[i] == ugly[ind_3]*3: ind_3+=1
if ugly[i] == ugly[ind_5]*5: ind_5+=1
return ugly[n-1]