【代码随想录Day46】动态规划

139 单词拆分

https://leetcode.cn/problems/word-break/description/

拆单词是有顺序的,要先遍历背包再遍历物品。

class Solution {  //TO(n^2 * n(set.contains substring)), SO(n)
  public boolean wordBreak(String input, List<String> dict) {
    // array[i] represent whether or not the substring of input[0,1) can break
    //Assumption: input not null nor empty, dict not null nor empty
    boolean[] array = new boolean[input.length() + 1];
    array[0] = true;                              
    Set<String> set = toSet(dict);
    for (int i = 1; i <= input.length(); i++) {    
      for (int j = 0; j < i; j++) {               
        if (array[j] == true && set.contains(input.substring(j, i))) {     // subString begins at j, ends at i - 1
          array[i] = true;
          break;
        }
      }
    }
    return array[input.length()];
  }
  private Set<String> toSet(List<String> dict) {
    Set<String> set = new HashSet<>();
    for (String s : dict) {
      set.add(s);
    }
    return set;
  }
}

背包总结篇非常有用

https://programmercarl.com/%E8%83%8C%E5%8C%85%E6%80%BB%E7%BB%93%E7%AF%87.html

问能否能装满背包(或者最多装多少):dp[j] = max(dp[j], dp[j - nums[i]] + nums[i]); ,对应题目如下:

问装满背包有几种方法:dp[j] += dp[j - nums[i]] ,对应题目如下:

问背包装满最大价值:dp[j] = max(dp[j], dp[j - weight[i]] + value[i]); ,对应题目如下:

问装满背包所有物品的最小个数:dp[j] = min(dp[j - coins[i]] + 1, dp[j]); ,对应题目如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值