动态规划part 06

LC 279.完全平方数

思路跟LC 322 零钱兑换那道题如出一辙,将n理解为背包容量,完全平方数理解为物品即可。

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

JAVA版本

java 复制代码
class Solution {
    public int numSquares(int n) {
        int[] dp = new int [n+1];
        for(int i = 1 ; i < dp.length ; i ++ ){
            dp[i] = Integer.MAX_VALUE;
        }
        for(int i = 1 ; i*i <= n ; i++){
            for(int j = i*i ; j <= n ; j ++){
                dp[j] = Math.min(dp[j - i*i] + 1 , dp[j]);
            }
        }
        return dp[n];
    }
}

和LC 322 的一个小区别在于,本题不需要判断"if dp[j - i*i] == Integr.max",因为本题是一定能凑成的,1可以凑成所有数字。

LC 139.单词拆分

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

是真难想,换一个题,dp数组的含义和递推公式就不会了。。。。

本题中,dp[ i ]的含义是,长度为 i 的字符串,是否能被字典里的单词构成 。

递推公式: 假设 s = "applepen" ,dp[s.length]就代表s能否被字典里的单词构成,它的结果依赖于子字符串(比如apple),apple得能被字典里的单词构成,并且,子字符串到当前字符串之间的字符串,也是出现在字典中,

相关推荐
聚客AI16 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v18 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工20 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农21 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
moonlifesudo1 天前
322:零钱兑换(三种方法)
算法
NAGNIP2 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队2 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法