leetcode-313-超级丑数

题目描述:

 

 方法一:动态规划 O(Nk)

class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: 
        dp = [1] * n
        l = [0]*len(primes)
        for i in range(1,n):
            dp[i] = min(dp[l[j]]*primes[j] for j in range(len(l)))
            for j in range(len(l)):
                if dp[l[j]]*primes[j]<=dp[i]:
                    l[j]+=1
        return dp[-1]

方法二;堆 O(knlogn)

class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int: 
        import heapq
        heap = [1]
        heapq.heapify(heap)
        for _ in range(n):
            res = heapq.heappop(heap)
            while heap and res==heap[0]:
                res = heapq.heappop(heap)
            for i in primes:
                heapq.heappush(heap,i*res)
        return res

 

posted @ 2019-10-11 10:33  oldby  阅读(155)  评论(0编辑  收藏  举报