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