[Leetcode] World Ladder
来源:互联网 发布:淘宝买微博粉丝怎么买 编辑:程序博客网 时间:2024/04/29 14:21
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"
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.
ANSWER:
class Solution {public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<string> currentseq; int shortest=dict.size()+1; vector<vector<string>> resultseqs; int currentsteps=0; helper(start,end,dict,shortest,currentsteps,currentseq,resultseqs); return resultseqs; } void helper(string start, string end, unordered_set<string> &dict, int &shortest, int currentsteps, vector<string> currentseq, vector<vector<string>> &resultseqs) { currentseq.push_back(start); if(start==end && currentsteps < shortest) { resultseqs.clear(); shortest=currentsteps; resultseqs.push_back(currentseq); } else if(start==end && currentsteps == shortest) { resultseqs.push_back(currentseq); } else if(start==end || currentsteps==dict.size()) return; //traverse throughput the dict to find one-change strings auto a=dict.begin(); //用迭代器遍历一个unsorted_set string strdict; for(int i=0;i<dict.size();i++) { strdict= *a; if(noexist(currentseq,strdict) && oneChange(start,strdict)) { helper(strdict,end,dict,shortest,currentsteps+1,currentseq,resultseqs); } a++; } } bool noexist(vector<string> strsets, string str) { for(int i=0;i<strsets.size();i++) { if(strsets.at(i) == str) return false; } return true; } bool oneChange(string a, string b) { if(a.length()!=b.length()) return false; int samecnt=0; for(int i=0;i<a.length();i++) { if(a[i] == b[i]) samecnt++; } if(samecnt==a.length()-1) return true; else return false; }};unsorted_set<int/string/...> 用法: http://www.cplusplus.com/reference/unordered_set/unordered_set/
- [Leetcode] World Ladder
- [Leetcode] Word Ladder
- LeetCode: Word Ladder
- leetcode 84: Word Ladder
- [leetcode] word ladder
- 【leetcode】Word Ladder
- 【leetcode】Word Ladder II
- LeetCode - Word Ladder
- LeetCode之Word Ladder
- [LeetCode]Word Ladder
- [LeetCode]Word Ladder II
- [Leetcode]Word Ladder
- [leetcode]Word Ladder
- [leetcode] Word Ladder
- [leetcode] Word Ladder II
- LeetCode-Word Ladder
- LeetCode- Word Ladder
- LeetCode - Word Ladder II
- 要成为优秀程序猿的建议
- pat 1030 Travel Plan
- BlackBerry10 开发环境搭建
- linux服务deamon
- 程序猿 技术不是你的全部
- [Leetcode] World Ladder
- 去百度还是去创新工厂? 信开复还是信彦宏?
- 一个简单确有用的有限状态机(FSM) in c++
- 黑客注入攻击入门
- Subversion服务器搭建
- 使用SQL Server Analysis Services数据挖掘的关联规则实现商品推荐功能(四)
- 学习Linux的第1天
- 学习LInux的第2天
- UVA 10082 - WERTYU