leetcode 126-Word Ladder II(hard)
Posted yshi12
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 126-Word Ladder II(hard)相关的知识,希望对你有一定的参考价值。
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.
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.
cases:
1. (the last word in tinylist)==endword, add tinylist to list and return;
2. iterate through tinylist, jump those already in the tinylist, check whether the word can be add to the tinylist(only one different letter with the last word in tinylist), if valid, add it to the tinylist;
most straight forward thought, can pass the test case given, but submit will tle.
class Solution { int minlen=Integer.MAX_VALUE; int start=0; public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { List<List<String>> list=new ArrayList<>(); if(wordList.size()==0) return list; List<String> tinylist=new ArrayList<String>(); tinylist.add(beginWord); find(endWord, wordList, list, tinylist); for(int i=0;i<start;i++) list.remove(0); return list; } public void find(String endWord, List<String> wordList, List<List<String>> list, List<String> tinylist){ String word=tinylist.get(tinylist.size()-1); if(word.equals(endWord)){ if(tinylist.size()<=minlen){ if(tinylist.size()<minlen){ minlen=tinylist.size(); start=list.size(); } list.add(new ArrayList(tinylist)); } return; } for(String str: wordList){ if(!tinylist.contains(str)){ if(check(str,word)){ tinylist.add(str); find(endWord, wordList, list, tinylist); tinylist.remove(tinylist.size()-1); } } } } public boolean check(String s, String p){ boolean flag=false; for(int i=0;i<s.length();i++){ if(s.charAt(i)!=p.charAt(i)){ if(flag) return false; else flag=true; } } return true; } }
leetcode上大佬们的答案太长了,改天再钻研这题补充正确答案好了。。(待更新)
以上是关于leetcode 126-Word Ladder II(hard)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 126. Word Ladder II 单词接龙 II(困难)