day38-dynamic programming-part06-8.9

tasks for today:

1. 322.零钱兑换

2. 279.完全平方数

3. 139.单词拆分

----------------------------------------------------------------------------

1. 322.零钱兑换

for 1-dim dp: the 01/complete decide the traverse sequence (descend/ascend) of backpack capability, the combination/permutation decide the choice of object-capability or capability-object.

deriving the number of solutions, should use dp[j] += d[j - nums[i]], with initialization of dp = [0] * (maxcapability+1) but with dp[0] = 1

min num of object (not the number of solutions): dp[j] = min(dp[j], dp[j-coins[i]]+1), with dp = [float('inf')] * (maxcap+1), dp[0] = 0

max value: dp[j] = max(dp[j], dp[j-weight[i]]+value[i]), with dp = [0] * (maxcap+1)

min value: dp[j] = min(dp[j], dp[j-weight[i]]+value[i]), with dp = [float('inf')] * (maxcap+1)

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)
        dp[0] = 0

        for i in range(len(coins)):
            for j in range(coins[i], amount+1):
                dp[j] = min(dp[j], dp[j-coins[i]]+1)
        
        if dp[-1] == float('inf'):
            return -1
        else:
            return dp[-1]

2. 279.完全平方数

In this practice, the key is how to control the traverse of object, because there is not a specific given limit on the object weight, which need to be find by ourselves which is hidden in the description, that is the i**2 <= n;

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [float('inf')] * (n+1)
        dp[0] = 0
        i = 1
        while i**2 <= n:
            for j in range(i**2, n+1):
                dp[j] = min(dp[j], dp[j-i**2] + 1)
            i += 1
        
        if dp[-1] == float('inf'):
            return -1
        else:
            return dp[-1]

3. 139.单词拆分

this practice has a reverse setting, which is not the usual setting that give the objects and try to derive the combination or the permutation for the arrangement of backpack. Instead, this practice give the permutation of backpack, and ask some questions about the objects.

One key pitfall in this practice is that the backpack, which is the string s in this practice, is a permutation problem.

In this practice, it is the first time so far for us to use boolen value for each entry in the dp list.

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [False] * (len(s) + 1)
        dp[0] = True
        for j in range(1, len(s)+1):
            for i in range(j):
                if (dp[i] and (s[i:j] in wordDict)):
                    dp[j] = True
                    break
        
        return dp[-1]

  • 30
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值