楼主: temperlancer
跳转到指定楼层
上一主题 下一主题
收起左侧

亚麻Onsite

🔗
user123456 2019-6-10 13:47:42 | 只看该作者
全局:
[quote]害群之蚂蚁 发表于 2019-5-14 05:30
  1. public class Coin_Word_Backtracking {
  2.     public boolean find(String[] coins ...[/quote]
  3. 嗯,我也感觉第二轮用backtrack毕竟靠谱。下面是我写的,大概看了一下,似乎思路差不多?

  4. [code]  public boolean formLetter(char[][] list, String word) {
  5.     // for every char character from A to Z, create a Set to store all the indices of coins where a char exists in the list
  6.     ArrayList<Set<Integer>> coinsForletter = new ArrayList<>();
  7.     for (int i = 0; i < 26; i++) {
  8.       coinsForletter.add(i, new HashSet<>());
  9.     }
  10.     for (int i = 0; i < list.length; i++) {
  11.       coinsForletter.get(list[i][0] - 'A').add(i);
  12.       coinsForletter.get(list[i][1] - 'A').add(i);
  13.     }
  14.     return backtrack(coinsForletter, word.toCharArray(), new HashSet<Integer>(),  0);
  15.   }
  16.   
  17.   // visited: a set of indices of coins that have already used one side (so we cannot use the other side anymore
  18.   private boolean backtrack(ArrayList<Set<Integer>> coinsForletter, char[] letters, Set<Integer> visited, int start) {
  19.     if (start >= letters.length) return true;
  20.    
  21.     char c = letters[start];
  22.     for (Integer coin : coinsForletter.get(c - 'A')) {
  23.       if (!visited.contains(coin)) {
  24.         visited.add(coin);
  25.         // if can continue all the way to the end, then it means we can return true for index `start`
  26.         if (backtrack(coinsForletter, letters, visited, start + 1)) return true;
  27.         // if backtrack() returns false above, it means that path cannot go through, so we backtrack
  28.         visited.remove(coin);
  29.       }
  30.     }
  31.     return false;
  32.   }
复制代码

补充内容 (2019-6-10 13:48):
这里假设所有字母都是大写字母。如果是任意unix code,那就换成Map<Character, Set<Integer>>就行了
回复

使用道具 举报

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

本版积分规则

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