Leetcode 313. super ugly number

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 313. super ugly number相关的知识,希望对你有一定的参考价值。

Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.

这道题和ugly number II 思路一样,关键是保留指针p,这个指针表明了下一次再乘p_i的时候应该和前面的哪一个ugly number相乘。

 

 1 class Solution(object):
 2     def nthSuperUglyNumber(self, n, primes):
 3         """
 4         :type n: int
 5         :type primes: List[int]
 6         :rtype: int
 7         """
 8         res = [1]*n
 9         m = len(primes)
10         p = [-1]*m
11         v = [1]*m
12         
13         for k in range(n):
14             res[k] = min(v)
15             for j in range(m):
16                 if v[j] == res[k]:
17                     p[j] += 1
18                     v[j] = res[p[j]]*primes[j]
19         return res[-1]

 

以上是关于Leetcode 313. super ugly number的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 313. Super Ugly Number

313. Super Ugly Number

313. Super Ugly Number

313. Super Ugly Number

力不从心 Leetcode(ugly number heap) 263, 264,313

<LeetCode OJ> 26 / 264 / 313 Ugly Number (I / II / III)