码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 313. super ugly number

时间:2016-12-02 14:12:22      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:div   class   pre   保留   who   res   super   amp   range   

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

标签:div   class   pre   保留   who   res   super   amp   range   

原文地址:http://www.cnblogs.com/lettuan/p/6125356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!