动态规划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得能被字典里的单词构成,并且,子字符串到当前字符串之间的字符串,也是出现在字典中,

相关推荐
尼尔森系3 小时前
排序与算法:希尔排序
c语言·算法·排序算法
AC使者4 小时前
A. C05.L08.贪心算法入门
算法·贪心算法
冠位观测者4 小时前
【Leetcode 每日一题】624. 数组列表中的最大距离
数据结构·算法·leetcode
yadanuof4 小时前
leetcode hot100 滑动窗口&子串
算法·leetcode
可爱de艺艺4 小时前
Go入门之函数
算法
武乐乐~4 小时前
欢乐力扣:旋转图像
算法·leetcode·职场和发展
a_j585 小时前
算法与数据结构(子集)
数据结构·算法·leetcode
清水加冰5 小时前
【算法精练】背包问题(01背包问题)
c++·算法
慢一点会很快7 小时前
FRRouting配置与OSPF介绍,配置,命令,bfd算法:
算法·智能路由器·php·ospf
88号技师8 小时前
2024年中科院一区SCI-雪雁优化算法Snow Geese Algorithm-附Matlab免费代码
开发语言·人工智能·算法·matlab·优化算法