LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

313. 超级丑数

超级丑数 是一个正整数,并满足其所有质因数都出现在质数数组 primes 中。

给你一个整数 n 和一个整数数组 primes ,返回第 n超级丑数

题目数据保证第 n超级丑数32-bit 带符号整数范围内。

示例 1:

输入:n = 12, primes = [2,7,13,19]
输出:32 
解释:给定长度为 4 的质数数组 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。

示例 2:

输入:n = 1, primes = [2,3,5]
输出:1
解释:1 不含质因数,因此它的所有质因数都在质数数组 primes = [2,3,5] 中。

提示:

数组 动态规划 中等

0264.丑数II 的更进一步

代码

1. 丑数II 的写法

时间 O(NM)

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

2. 动态规划 + 堆

时间压缩到 O(NlogM)

class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        m = len(primes)
        # dp[i] 代表第i+1个丑数
        dp = [1] * n
        pq = [(p, 0, i) for i,p in enumerate(primes)]

        for i in range(1, n):
            cur = pq[0][0]
            dp[i] = cur
            while pq and pq[0][0] == cur:
                _, idx, p = heapq.heappop(pq)
                heapq.heappush(pq, (dp[idx+1] * primes[p], idx + 1, p))
        return dp[-1]