第46天 Dynamic Programming 多重背包 139

多重背包:

  • 每个物品有不同的可用的数量,有自己的重量和价值

  • 方法1: 把多重背包转化成01背包,改weight和value

  • 方法2: 原来的两层for loop里再加一层for(int k=1; k<=nums[i]; k++)

  • Time Complexity: O(m × n × k),m:物品种类个数,n背包容量,k单类物品数量

139. Word Break

  • 方法1: 完全背包
  • 背包容量:s.length()
  • 物品个数:wordDict.length()
  • 物品重量:word.length() 且他是否和s.substring(j-word.length(), j)完全一样
  • 公式:dp[j] = true if dp[j-len] == true && word == s.substring(j-word.length(), j)
  • 初始化:dp[0] = true 概念上不合理,为了递推公式方便
  • 遍历顺序:先容量后物品,所以所有word都会match一遍,保证覆盖全部的 word == s.substring(j-word.length(), j) 情况
  • 注意//的地方,是先物品后容量,会有wordDict = [apple, pen], s = applepenapple, dp[s.length()] = false的情况,因为 word != s.substring(j-word.length(), j) 但其实是有之前遍历过的word == s.substring(j-word.length(), j)
  • 这里不像普通的完全背包,从小到大去遍历,就可以保证一个物品多次加入到背包,因为物品的重量word是否等于s.substring(j-word.length(), j)没有办法排序
class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;

        for (int j=0; j<=s.length(); j++) {
            for (int i=0; i<wordDict.size(); i++) {
                int len = wordDict.get(i).length();
                if (len <= j && dp[j-len] == true && wordDict.get(i).equals(s.substring(j-len, j)))
                    dp[j] = true;
            }
        }

        // for (int i=0; i<wordDict.size(); i++) {
        //     for (int j=wordDict.get(i).length(); j<=s.length(); j++) {
        //         int len = wordDict.get(i).length();
        //         if (dp[j-len] && wordDict.get(i).equals(s.substring(j-len, j)))
        //             dp[j] = true;
                
        //     }
        //     for (int j=0; j<=s.length(); j++)
        //         System.out.print(dp[j]+" ");
        //     System.out.println();
        // }

        return dp[s.length()];
    }
}

  • 方法2: 完全背包
  • 物品:单词,但其实是遍历s的所有字串
  • 背包:字符串s
  • 单词能否组成字符串s:物品能不能把背包装满 -> 完全背包
  • dp[j] : 字符串长度为j的话,dp[j]为true,表示可以拆分为一个或多个在字典中出现的单词
  • 递推公式:if (dp[i] 是true && [i, j] 这个区间的子串出现在字典里) dp[j] = true (i<j)
  • 遍历顺序:因为分割子串的特殊性,遍历背包放在外循环,将遍历物品放在内循环更方便一些。
  • 如果要是外层for循环遍历物品,内层for遍历背包,就需要把所有的子串都预先放在一个容器里。
  • Time Complexity: O(n^3),因为substr返回子串的副本是O(n)的复杂度(这里的n是substring的长度)
  • Space Complexity:O(n)
class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length()+1];
        dp[0] = true;

        for (int j=0; j<=s.length(); j++) {
            for (int i=0; i<j; i++) {
                if (dp[i] == true && wordDict.contains(s.substring(i, j)))
                    dp[j] = true;
            }
        }

        return dp[s.length()];
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值