756. Pyramid Transition Matrix 发表于 2018-10-28 | 分类于 leetcode 题目详见:https://leetcode.com/problems/pyramid-transition-matrix/ 思路:递归,回溯。 123456789101112131415161718192021222324252627282930313233343536class Solution {public: bool pyramidTransition(string bottom, vector<string>& allowed) { unordered_map<string,vector<char>> allowed_map; for(string element:allowed){ allowed_map[element.substr(0,2)].push_back(element.back()); } string current=""; return DFS(bottom,current,0,allowed_map); }private: //两个字母用一个字母代替 //pre未替换完的字符串 //current当前已替换完得到的字符串 //k,pre开始要替换的字母的index //dict包含可替换的选择 bool DFS(string& pre,string& current,int k,unordered_map<string,vector<char>>& dict){ if(pre.length()==1) return true; if(k+1==pre.length()){ string next=""; return DFS(current,next,0,dict); } else{ string key=pre.substr(k,2); if(dict.count(key)==0) return false; vector<char> value=dict[key]; for(auto c:value){ current.push_back(c); if(DFS(pre,current,k+1,dict)) return true; current.pop_back(); } return false; } } };