[leetcode]Word Ladder II
来源:互联网 发布:淘宝联盟买家 编辑:程序博客网 时间:2024/05/21 09:49
问题描述:
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) fromstart 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"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
代码:
void createResult(map<string,vector<string> >&record,vector<vector<string> >&result,string pre,string start,list<string>myList){ //C++ if(pre == start){ vector<string> vec(myList.begin(),myList.end()); result.push_back(vec); // for(int i=0; i<myList.size();i++) // vec.push_back(myList[i]); } vector<string> next = record[pre]; for(int i=0; i<next.size(); i++){ string word = next[i]; list<string> temp(myList); temp.push_front(word); createResult(record,result,word,start,temp); } } vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string> > result; int size = dict.size(); if(start.size() ==0 || end.size() ==0 || size==0 || start==end) return result; map<string,int> myMap; map<string,vector<string> > record; queue<string> myQueue; myQueue.push(start); myMap[start] = 1; string temp; while(!myQueue.empty()){ temp = myQueue.front(); myQueue.pop(); for(int i =0; i<temp.size(); i++){ string newword = temp; for(int j=0; j<26; j++){ newword[i] = 'a'+j; if(dict.count(newword)!=0){ if(myMap.count(newword)==0) { myMap[newword] = myMap[temp] +1; myQueue.push(newword); vector<string> vec; vec.push_back(temp); record.insert(make_pair(newword,vec)); } else if(myMap[newword] == myMap[temp]+1){ vector<string> vec = record[newword]; vec.push_back(temp); record[newword]=vec; } } } } } if(record.count(end)==0) return result; list<string> temp_list; temp_list.push_back(end); createResult(record,result,end,start,temp_list); }
0 0
- 【leetcode】Word Ladder II
- [LeetCode]Word Ladder II
- [leetcode] Word Ladder II
- LeetCode - Word Ladder II
- Leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode Word Ladder II
- LeetCode | Word Ladder II
- leetcode word ladder II
- 【Leetcode】Word Ladder II
- [LeetCode] Word Ladder II
- Word Ladder II -- LeetCode
- Leetcode: Word Ladder II
- leetcode-Word Ladder II
- leetcode-Word Ladder II
- leetcode: Word Ladder II
- leetcode Word Ladder II
- Leetcode: Word Ladder II
- C语言接口与实现: Atom
- iOS 创建一个滑出式导航面板
- iosApp系统拨打电话,发送邮件,跳转网址,openURL的使用
- 蛇行矩阵
- 压缩感知的几位鼻祖
- [leetcode]Word Ladder II
- 禁用ARC,解决“ARC forbids explicit message send of ‘release’”
- Visual C++ 游戏开发笔记 纹理映射技术(一)
- <Android>监听软键盘打开收起事件(软键盘自带收起按钮)
- 阻塞队列
- 【设计模式】-工厂模式(Factory)
- jquery表单实现表单序列化
- ARM M4特点
- android studio Gradle如果不能找依赖的包(Gradle can't find dependency (Android support library)),教你如何解决