标签:cas dup only not note array public void pre
Given two words (beginWord and endWord), and a dictionary‘s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Note:
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)
标签:cas dup only not note array public void pre
原文地址:https://www.cnblogs.com/yshi12/p/9691940.html