leetcode 264. Ugly Number II DP

来源:互联网 发布:thinkphp商城系统源码 编辑:程序博客网 时间:2024/06/10 22:04

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note that 1 is typically treated as an ugly number, and n does not exceed 1690.


import  heapqclass Solution(object):    def nthUglyNumber(self, n):        reslut = [1]        i = j = k = 0        while len(reslut) < n:            l = len(reslut)            nx = min(reslut[i]*2 , reslut[j]*3 , reslut[k]*5)            if reslut[i] * 2 == nx:                i += 1            if reslut[j] * 3 == nx:                j += 1            if reslut[k] * 5 == nx:                k += 1            reslut.append(nx)        return reslut[n-1]if __name__ == '__main__':    s = Solution()    print(s.nthUglyNumber(10))