动态规划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 dpj - 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" ,dps.length就代表s能否被字典里的单词构成,它的结果依赖于子字符串(比如apple),apple得能被字典里的单词构成,并且,子字符串到当前字符串之间的字符串,也是出现在字典中,

相关推荐
学究天人8 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷7)
线性代数·矩阵·动态规划·概率论·图论·抽象代数·拓扑学
alphaTao9 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10059 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
imuliuliang9 小时前
可合并堆在多任务调度中的优势与实现技巧7
算法
学究天人9 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学
wabs6669 小时前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
用户333239768849 小时前
我做了一个 RepoMind:让 AI 写架构前,先去看看真实开源项目
算法
chh56310 小时前
C++--list
开发语言·数据结构·c++·学习·算法·list
killerbasd10 小时前
总结 7。10
人工智能·算法·机器学习
林间码客10 小时前
RAG系统评估指南:从入门到实践
人工智能·算法·机器学习