Word Ladder II

这道题做了好长时间都没通过,参考了http://blog.csdn.net/niaokedaoren/article/details/8884938的实现,其中在求前驱单词记录时,申请的数组要采用vector<unordered_set<string>>这样,在判断是否结束时,查找效率更高,否则用前向单词记录表查找时效率会很低。

算法中的递归找paht可以用栈来避免递归,是一个优化点。

class Solution {
public:

      vector<vector<string>> wordsladders;

    vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {

		  unordered_map<string,vector<string>> forword;
		  dict.insert(end);
		  InitData(forword,dict);
		  bool ret;
		  ret = GetTraces(forword,start,end,dict);
	      if(ret == false)
		  	return wordsladders;
		  vector<string> path;
		  GetPath(end,forword,path);

	      return wordsladders;

    }
	void GetPath(string& tempstr,unordered_map<string,vector<string>> &forword,vector<string>& path)
    {

	  vector<string> result;
	  path.push_back(tempstr);

	  if(forword[tempstr].empty())
	  {
	     result.resize(path.size());
         copy(path.rbegin(), path.rend(),result.begin());
		 wordsladders.push_back(result);
		 path.pop_back();
         return ;
	  }

      for(auto ite = forword[tempstr].begin(); ite!= forword[tempstr].end(); ite++)
      {
      	 GetPath(*ite,forword,path);
	  }
	  path.pop_back();

	}
	void InitData(unordered_map<string,vector<string>> &forword,unordered_set<string> &dict)
	{
	   unordered_set<string>::iterator ite;
	   pair<string,vector<string>> temp;
       for(ite = dict.begin(); ite!= dict.end(); ite++)
       {
          temp.first = *ite;
          forword.insert(temp);
	   }

	}
	bool GetTraces(unordered_map<string,vector<string>> &forword,string& start,string& end,unordered_set<string> &dict)
	{
	      vector<unordered_set<string> > buf(2);
		  int cur,pre;
          cur =0;
		  pre =1;
		  string tempstr;
		  buf[0].insert(start);
		  while(1)
		  {
			   cur = !cur;
			   pre = !pre;
	           for(auto ite = buf[pre].begin(); ite != buf[pre].end(); ite++)
	           {
	               dict.erase(*ite);
			   }
			   for(auto ite = buf[pre].begin(); ite!= buf[pre].end(); ite++)
			   {
	               for(int i = 0; i < (*ite).size(); i++)
			       {
			           tempstr = *ite;
			           for(int j=0; j< 26;j++)
			           {

			             if(‘a‘+j == tempstr[i])
						  continue ;
						 tempstr[i] = ‘a‘+j;
						 if(dict.find(tempstr) == dict.end())
						   continue;
						 forword[tempstr].push_back(*ite);
						 buf[cur].insert(tempstr);
					   }

				  }

			 }
			 buf[pre].clear();
			 if(buf[cur].size() == 0)
			 	return false;
			 if(buf[cur].count(end))
			 	 return true;

		}

   }

};

  

时间: 2024-10-29 19:07:36

Word Ladder II的相关文章

18. Word Ladder &amp;&amp; Word Ladder II

Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example,

[leetcode]Word Ladder II @ Python

[leetcode]Word Ladder II @ Python 原题地址:http://oj.leetcode.com/problems/word-ladder-ii/ 参考文献:http://blog.csdn.net/doc_sgl/article/details/13341405   http://chaoren.is-programmer.com/ 题意:给定start单词,end单词,以及一个dict字典.要求找出start到end的所有最短路径,路径上的每个单词都要出现在dict

Word Ladder II leetcode java

题目: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example, Given: start =

[python leetcode] Word Ladder II (very hard)[非常难,放弃]

Word Ladder II 描述 Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: • Only one letter can be changed at a time • Each intermediate word must exist in the dictionary For examp

126. Word Ladder II(js)

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

leetcode Word Ladder II

和上题 Word Ladder I题目差不多,不过这里是要记录所有最段路径的可能. 不同点在于,我们不能再BFS每层的时候把相距一个字符的字符串在dict中删除,因为hot -> hit 的话其他的例如 jit -> hit 就是hit可以出现在两条路径里头.所以不能立马删除.但是我们发现我们可以删除的是我们遍历完的每层的字符串,我们用known来存遍历完的层,unknown来存没有遍历的层,那么每次求得下一层unknown的时候,就首先把known里面有的从dic中删除. 主要思路还是和上一

[Leetcode][JAVA] Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary For example, Given:start = "hit

【leetcode】126. Word Ladder II

题目如下: 解题思路:DFS或者BFS都行.本题的关键在于减少重复计算.我采用了两种方法:一是用字典dic_ladderlist记录每一个单词可以ladder的单词列表:另外是用dp数组记录从startword开始到wordlist每一个word的最小转换次数,这一点非常重要,可以过滤很多无效的运算. 代码如下: class Solution(object): def getLadderList(self, w,d): l = [] r = [] for i in xrange(26): l.a

leetcode 126. Word Ladder II

1 import string 2 import collections 3 4 class Solution(object): 5 def findLadders(self, begin, end, words_list): 6 '''删除起至单词''' 7 words_list.discard(begin) 8 words_list.discard(end) 9 10 '''根据tree递归构造路径''' 11 def construct_paths(source, dest, tree):

leetcode&mdash;&mdash;Word Ladder II

    改了3个晚上终于没有bug了...结果超时了...我已经想不出该怎么优化了....看了答案,是一层一层遍历,然后将每个单词的父节点push进一个vector里,我也是一层层,并且如果在下一层遇到上一层的某个单词,就记录单词被访问过,就不会再访问了...就是想不明白为啥用的时间要多很多...难道是因为我的代码不够简洁么?!!... class Solution { // 用广度搜索,建立由start开始的搜索树,子节点为父节点只改变一个字母在字典里能查到的所有的单词 // 每个子节点能记录