Leetcode Summary: Ugly number

[264] Ugly Number II

class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<=0:
            return 0
        if n==1:
            return 1

        dp=[0 for i in range(n)]

        t2=0
        t3=0
        t5=0
        dp[0]=1

        for i in range(1,n):
            dp[i]=min(2*dp[t2],3*dp[t3],5*dp[t5])
            val=dp[i]

            if val==2*dp[t2]:
                #dp[t2]=val
                t2+=1
            if val==3*dp[t3]:
                #dp[t3]=val
                t3+=1
            if val==5*dp[t5]:
                #dp[t5]=val
                t5+=1

        return dp[n-1]

313. Super Ugly Number

same idea with ugly number II, use a list to hold the count of all primes

Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [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.

class Solution(object):
    def nthSuperUglyNumber(self, n, primes):
        """
        :type n: int
        :type primes: List[int]
        :rtype: int
        """
        ret=0
        dp=[1 for i in range(n)]
        cnt=[0 for i in range(len(primes))]
        
        for i in range(1,n):
            dp[i]=min([primes[k]*dp[cnt[k]] for k in range(len(primes))])
            for k in range(len(primes)):
                if dp[i]==primes[k]*dp[cnt[k]]:
                    cnt[k]+=1
                    #break  # cannot break, all combination should plus one when equal to the target: like 2*7=14, and also 7*2=14
        #print dp            
        return dp[-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值