leetcode题解-126. Word Ladder II

题目:

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]
Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

这道题挺难的==先翻译一下题目,其实是给定了一个beginWord和endWord,还有可用的单词列表,然后我们需要在每次只转换一个字符且转换后的字符在wordList中的情况下,将beginWord在最短步骤内转换为endWord,看到题目没有什么好的思路,然后正好前两天有同学问我dfs的一道题目,发现与本题有那么一丢丢的相似,然后就想着强行套dfs,中途遇到了几个问题:

  • 如何解决每次只转换一个字符
  • 如何解决在最短步骤内完成转换
    然后也是想了很久才把这道题目做出来,代码如下所示:
    static int min = Integer.MAX_VALUE;
    public static List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
        //存储返回结果
        List<List<String>> res = new ArrayList<>();
        //存储当前的路径
        List<String> tmp = new ArrayList<>();
        tmp.add(beginWord);
        //因为题目要求endWord必须在wordList中,否则报错
        if(!wordList.contains(endWord))
            return res;
        //调用dfs方法求解
        dfs(res, tmp, beginWord, endWord, wordList);
        //此时res中存储了所有的可行解,但有些并不是步骤最短解,所以需要用全局变量min来记录最短步骤,然后将大于min的结果删除
        for(int i=0; i<res.size(); i++){
            if(res.get(i).size() > min) {
                res.remove(i);
                i--;
            }
        }
        System.out.println(res.toString());
        return res;
    }
        public static void dfs(List<List<String>> res, List<String> tmp, String beginWord, String endWord, List<String> wordList){
        //dfs函数返回标志,当现在要遍历的单词与endWord只差一个字符时,说明已经满足要求,将其插入tmp,并将tmp插入res即可
        if(isOne(beginWord, endWord)){
            tmp.add(endWord);
            min = Math.min(min, tmp.size());
            res.add(new ArrayList<>(tmp));
            tmp.remove(endWord);
            return;
        }
        //否则,说明还未找到解,继续遍历数组
        for(String tt : wordList){
            //若当前词不在tmp中且与beginWord只差一个字符,则将其插入tmp,并继续调用dfs函数继续执行
            if(!tmp.contains(tt) && isOne(beginWord, tt)){
                tmp.add(tt);
                dfs(res, tmp, tt, endWord, wordList);
                //=当执行dfs找到一个可行解之后,删除当前词,继续遍历下一个词
                tmp.remove(tt);
            }

        }
    }
    //判断两个词是否只相差一个字符
    public static boolean isOne(String s, String t){
        int k=0;
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i) != t.charAt(i))
                k++;
        }
        if(k == 1)
            return true;
        else
            return false;
    }

恩,上面就是我的方法,但是,很明显,由于中间重复计算次数太多而且是先找出所有可行解之后在将非最优解去掉,所以算法效率很低,也爆出了超出时间限制的错误。所以去网上找了一下别人实现的方法,发现大部分都是先用BFS找到最短步骤数,并将一些相关信息使用HashMap保存,然后再使用DFS遍历保存下来的neighbor和distance信息,找出符合要求的结果,大概是因为Word Ladder I那个题目中延续下来的方法。先不管这么多,我们来看一下代码:

public List<List<String>> findLadders(String start, String end, List<String> wordList) {
   HashSet<String> dict = new HashSet<String>(wordList);
   List<List<String>> res = new ArrayList<List<String>>();         
   HashMap<String, ArrayList<String>> nodeNeighbors = new HashMap<String, ArrayList<String>>();// 保存每个节点的neighbor信息,也就是相差一个字符的所有组合
   HashMap<String, Integer> distance = new HashMap<String, Integer>();// 记录每个字符串到beginWord的距离
   ArrayList<String> solution = new ArrayList<String>();

   dict.add(start);          
   bfs(start, end, dict, nodeNeighbors, distance);                 
   dfs(start, end, dict, nodeNeighbors, distance, solution, res);   
   return res;
}

// BFS: Trace every node's distance from the start node (level by level).
private void bfs(String start, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance) {
  for (String str : dict)
      nodeNeighbors.put(str, new ArrayList<String>());
    //使用队列进行BFS遍历
  Queue<String> queue = new LinkedList<String>();
  queue.offer(start);
  distance.put(start, 0);

  while (!queue.isEmpty()) {
      int count = queue.size();
      boolean foundEnd = false;
      for (int i = 0; i < count; i++) {
          String cur = queue.poll();
          int curDistance = distance.get(cur);                
          ArrayList<String> neighbors = getNeighbors(cur, dict);

          for (String neighbor : neighbors) {
              nodeNeighbors.get(cur).add(neighbor);
              if (!distance.containsKey(neighbor)) {// Check if visited
                  distance.put(neighbor, curDistance + 1);
                  if (end.equals(neighbor))// Found the shortest path
                      foundEnd = true;
                  else
                      queue.offer(neighbor);
                  }
              }
          }

          if (foundEnd)
              break;
      }
  }

// Find all next level nodes.    
private ArrayList<String> getNeighbors(String node, Set<String> dict) {
  ArrayList<String> res = new ArrayList<String>();
  char chs[] = node.toCharArray();

  for (char ch ='a'; ch <= 'z'; ch++) {
      for (int i = 0; i < chs.length; i++) {
          if (chs[i] == ch) continue;
          char old_ch = chs[i];
          chs[i] = ch;
          if (dict.contains(String.valueOf(chs))) {
              res.add(String.valueOf(chs));
          }
          chs[i] = old_ch;
      }

  }
  return res;
}

// DFS: output all paths with the shortest distance.
private void dfs(String cur, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance, ArrayList<String> solution, List<List<String>> res) {
    solution.add(cur);
    if (end.equals(cur)) {
       res.add(new ArrayList<String>(solution));
    } else {
       for (String next : nodeNeighbors.get(cur)) {            
            if (distance.get(next) == distance.get(cur) + 1) {
                 dfs(next, end, dict, nodeNeighbors, distance, solution, res);
            }
        }
    }           
   solution.remove(solution.size() - 1);
}

上面这种方法可以击败67%的用户,可以说使用额外的存储空间大大的降低了时间复杂度,我想这也应该是一种常用的降低时间复杂度的方法吧,不过其内在的思路还是十分值得我们学习的。然后还找到一中可以击败97%的方法,想法更加完美,使用双向BFS来加速,具体思路可以参考链接,但是由于题目更改,现在代码是无法直接运行的,可以参考我改过之后的==代码入下:

public class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
    //we use bi-directional BFS to find shortest path
    List<List<String>> result = new ArrayList<List<String>>();
    if(!wordList.contains(endWord))
        return result;
    HashSet<String> dict = new HashSet<String>(wordList);
    Set<String> fwd = new HashSet<String>();
    fwd.add(beginWord);

    Set<String> bwd = new HashSet<String>();
    bwd.add(endWord);

    Map<String, List<String>> hs = new HashMap<String, List<String>>();
    BFS(fwd, bwd, dict, false, hs);



    //if two parts cannot be connected, then return empty list
    if(!isConnected) return result;

    //we need to add start node to temp list as there is no other node can get start node
    List<String> temp = new ArrayList<String>();
    temp.add(beginWord);

    DFS(result, temp, beginWord, endWord, hs);

    return result;
}

//flag of whether we have connected two parts
boolean isConnected = false;

public void BFS(Set<String> forward, Set<String> backward, Set<String> dict, boolean swap, Map<String, List<String>> hs){

    //boundary check
    if(forward.isEmpty() || backward.isEmpty()){
        return;
    }

    //we always do BFS on direction with less nodes
    //here we assume forward set has less nodes, if not, we swap them
    if(forward.size() > backward.size()){
        BFS(backward, forward, dict, !swap, hs);
        return;
    }

    //remove all forward/backward words from dict to avoid duplicate addition
    dict.removeAll(forward);
    dict.removeAll(backward);

    //new set contains all new nodes from forward set
    Set<String> set3 = new HashSet<String>();

    //do BFS on every node of forward direction
    for(String str : forward){
        //try to change each char of str
        for(int i = 0; i < str.length(); i++){
            //try to replace current char with every chars from a to z 
            char[] ary = str.toCharArray();
            for(char j = 'a'; j <= 'z'; j++){
                ary[i] = j;
                String temp = new String(ary);

                //we skip this string if it is not in dict nor in backward
                if(!backward.contains(temp) && !dict.contains(temp)){
                    continue;
                }

                //we follow forward direction    
                String key = !swap? str : temp;
                String val = !swap? temp : str;

                if(!hs.containsKey(key)) hs.put(key, new ArrayList<String>());

                //if temp string is in backward set, then it will connect two parts
                if(backward.contains(temp)){
                    hs.get(key).add(val);
                    isConnected = true;
                }

                //if temp is in dict, then we can add it to set3 as new nodes in next layer
                if(!isConnected && dict.contains(temp)){
                    hs.get(key).add(val);
                    set3.add(temp);
                }
            }

        }
    }

    //to force our path to be shortest, we will not do BFS if we have found shortest path(isConnected = true)
    if(!isConnected){
        BFS(set3, backward, dict, swap, hs);
    }
}

public void DFS(List<List<String>> result, List<String> temp, String start, String end, Map<String, List<String>> hs){
    //we will use DFS, more specifically backtracking to build paths

    //boundary case
    if(start.equals(end)){
        result.add(new ArrayList<String>(temp));
        return;
    }

    //not each node in hs is valid node in shortest path, if we found current node does not have children node,
    //then it means it is not in shortest path
    if(!hs.containsKey(start)){
        return;
    }

    for(String s : hs.get(start)){
        temp.add(s);
        DFS(result, temp, s, end, hs);
        temp.remove(temp.size()-1);

    }
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,我来用中文回复这个链接:https://leetcode-cn.com/tag/dynamic-programming/ 这个链接是 LeetCode 上关于动态规划的题目集合。动态规划是一种常用的算法思想,可以用来解决很多实际问题,比如最长公共子序列、背包问题、最短路径等等。在 LeetCode 上,动态规划也是一个非常重要的题型,很多题目都需要用到动态规划的思想来解决。 这个链接里包含了很多关于动态规划的题目,按照难度从简单到困难排列。每个题目都有详细的题目描述、输入输出样例、题目解析和代码实现等内容,非常适合想要学习动态规划算法的人来练习和提高自己的能力。 总之,这个链接是一个非常好的学习动态规划算法的资源,建议大家多多利用。 ### 回答2: 动态规划是一种算法思想,通常用于优化具有重叠子问题和最优子结构性质的问题。由于其成熟的数学理论和强大的实用效果,动态规划在计算机科学、数学、经济学、管理学等领域均有重要应用。 在计算机科学领域,动态规划常用于解决最优化问题,如背包问题、图像处理、语音识别、自然语言处理等。同时,在计算机网络和分布式系统中,动态规划也广泛应用于各种优化算法中,如链路优化、路由算法、网络流量控制等。 对于算法领域的程序员而言,动态规划是一种必要的技能和知识点。在LeetCode这样的程序员平台上,题目分类和标签设置十分细致和方便,方便程序员查找并深入学习不同类型的算法。 LeetCode的动态规划标签下的题目涵盖了各种难度级别和场景的问题。从简单的斐波那契数列、迷宫问题到可以用于实际应用的背包问题、最长公共子序列等,难度不断递进且话题丰富,有助于开发人员掌握动态规划的实际应用技能和抽象思维模式。 因此,深入LeetCode动态规划分类下的题目学习和练习,对于程序员的职业发展和技能提升有着重要的意义。 ### 回答3: 动态规划是一种常见的算法思想,它通过将问题拆分成子问题的方式进行求解。在LeetCode中,动态规划标签涵盖了众多经典和优美的算法问题,例如斐波那契数列、矩阵链乘法、背包问题等。 动态规划的核心思想是“记忆化搜索”,即将中间状态保存下来,避免重复计算。通常情况下,我们会使用一张二维表来记录状态转移过程中的中间值,例如动态规划求解斐波那契数列问题时,就可以定义一个二维数组f[i][j],代表第i项斐波那契数列中,第j个元素的值。 在LeetCode中,动态规划标签下有众多难度不同的问题。例如,经典的“爬楼梯”问题,要求我们计算到n级楼梯的方案数。这个问题的解法非常简单,只需要维护一个长度为n的数组,记录到达每一级楼梯的方案数即可。类似的问题还有“零钱兑换”、“乘积最大子数组”、“通配符匹配”等,它们都采用了类似的动态规划思想,通过拆分问题、保存中间状态来求解问题。 需要注意的是,动态规划算法并不是万能的,它虽然可以处理众多经典问题,但在某些场景下并不适用。例如,某些问题的状态转移过程比较复杂,或者状态转移方程中存在多个参数,这些情况下使用动态规划算法可能会变得比较麻烦。此外,动态规划算法也存在一些常见误区,例如错用贪心思想、未考虑边界情况等。 总之,掌握动态规划算法对于LeetCode的学习和解题都非常重要。除了刷题以外,我们还可以通过阅读经典的动态规划书籍,例如《算法竞赛进阶指南》、《算法与数据结构基础》等,来深入理解这种算法思想。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值