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

  1. Only one letter can be changed at a time
  2. 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上大佬们的答案太长了,改天再钻研这题补充正确答案好了。。(待更新)

posted on 2018-09-23 08:14  elsie12  阅读(79)  评论(0编辑  收藏  举报