LeetCode 第三十天2024.8.15

1. :零钱兑换
 题目链接: 322. 零钱兑换 - 力扣(LeetCode)
应用条件:

难点:
# 确定dp数组(dp table)以及下标的含义:dp[j]表示凑成amount需要的硬币最少个数
# 确定递推公式: dp[j] min(dp[j-coins[i]]+1,dp[j])
# dp数组如何初始化:  dp[0]=0
# 确定遍历顺序: 组合先物品再背包 i从0到len(coins) j从0到amount

个人错误:

思路:

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(amount+1):
                if j >= coins[i]:
                    dp[j] = min(dp[j-coins[i]]+1,dp[j])
        if dp[amount] == float(inf):
            return -1
        else:
            return dp[amount]

2. :完全平方数
 题目链接: 279. 完全平方数 - 力扣(LeetCode)
应用条件:

难点:

# 确定dp数组(dp table)以及下标的含义:dp[j]表示和为 n 的完全平方数的最少数量 
# 确定递推公式: dp[j] min(dp[j-nums[i]]+1,dp[j])
# dp数组如何初始化:  dp[0]=0
# 确定遍历顺序: 组合先物品再背包 i从0到len(coins) j从0到amount+1

个人错误:

思路:

class Solution:
    def numSquares(self, n: int) -> int:
        nums = []
        for i in range( int(n ** 0.5) + 1):
            nums.append(i*i)
        dp = [float(inf)]*(n+1)
        dp[0] = 0
        # dp[1] = 1
        for i in range(len(nums)):
            for j in range(n+1):
                if j >= nums[i]:
                    dp[j] = min(dp[j-nums[i]]+1,dp[j])
        print(dp)
        if dp[n] == float(inf):
            return -1
        else:
            return dp[n]

3. :单词拆分
 题目链接: 139. 单词拆分 - 力扣(LeetCode)
应用条件:

难点:

# 确定dp数组(dp table)以及下标的含义:dp[j]表示长度到j的s能否被单词组成。 
# 确定递推公式: i从0到j 如果存在dp[i]是true以及dp[j-i]是true那么dp[j]也是true
# dp数组如何初始化:  dp[0]=true
# 确定遍历顺序: 这道题只能先背包再物品,因为物品有顺序,例如"apple" "pen" "apple"和"apple" "apple" "pen" 不一样 所以,j从0到len(s) i从0到j 

个人错误:

思路:

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[len(s)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值