查看: 1219| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] 求问这道算法题该怎么解

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
Given a collection of blocks with letters on them, and a target word, determine if the blocks can form the target word

(B,A),(A,B),(X,Y),(A,B): "BABY" => yes
(B,A),(A,B),(L,E),(A,B): "ABLE" => no (since L and E are on the same block).

我想到的就是可以用dfs来找某个与target word对应的切入点,然后看是否能匹配整个word, 以下是我的代码


  1. class solutions {

  2.       public boolean solution(List<List<String>> wordList, String target) {

  3.         if (target.length() > wordList.size()) return false;
  4.         Map<String, Integer> hm = new HashMap<>();
  5.         for (char c : target.toCharArray()) {
  6.                 hm.put(c + “”, hm.getOrDefault(c, 0) + 1);
  7.         }
  8.         return formWordPairsHelper(wordList, hm, target.length(), new HashSet<>());
  9. }

  10.     public boolean formWordPairsHelper(List<List<String>> wordList, Map<String, Integer> hm, int count, Set<Integer> visited) {
  11.         if (visited.size() == wordList.size()) {
  12.                 if (count == 0) return true;
  13.                 return false;
  14.         }
  15.         for (int i = 0; i < wordList.size(); i++) {
  16.                 for (String s : wordList.get(i)) {
  17.                 if (!visited.contains(i) && hm.containsKey(s) && hm.get(s) > 0) {
  18.                 hm.put(s, hm.get(s) - 1);
  19.                 visited.add(i)
  20.                 boolean res = formWordPairsHelper(wordList, hm, count - 1, visited);
  21.                 if (res) return true;
  22.                 visited.remove(i);       
  23.                 hm.put(s, hm.get(s) + 1);
  24.                 }
  25. }
  26.         }
  27.         return count == 0;

  28. }
复制代码



还请大神看一看这样写对不对

上一篇:what's the difference between PR AUC &amp; ROC AUC
下一篇:发工资啦,LeetCode每日一题全勤12月
全局:
应该是dfs,先从出现频次少的开始搜应该可以减少搜索空间。
回复

使用道具 举报

🔗
cynthiazhxu 2021-1-2 13:46:21 | 只看该作者
全局:
本帖最后由 autumnhu 于 2021-1-2 13:50 编辑

像是一道二分图匹配题:
如果某个block拥有某个position的字母话,这个block和这个position之间连一条边。然后看这个二分图的最大匹配数是否等于target word的长度。用匈牙利算法的话复杂度是O(V⋅E),V为边数,E为点数(block数量+target word长度),比DFS指数级的复杂度要快一些。
Example 1:
Block 0 连 Position 0, 1, 2
Block 1 连 Position 3
Block 2 连 Position 0, 1, 2
Block 3 连 Position 0, 1, 2

最大匹配数为4,所以输出yes
回复

使用道具 举报

🔗
usr_opta 2021-1-2 14:52:06 | 只看该作者
全局:
经典二分图匹配
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表