2
HashMap<String, List<Character>> map = new HashMap<>();3
HashMap<String, Boolean> dp = new HashMap<>();5
public boolean pyramidTransition(String bottom, List<String> allowed) {6
for (String s : allowed) {7
String sub = s.substring(0, 2);11
if (!map.containsKey(sub)) map.put(sub, new ArrayList<>());16
return dfs(bottom, "", 0);19
boolean dfs(String currBottom, String newBottom, int index) {21
if (currBottom.length() == 1) return true;22
if (index + 1 >= currBottom.length()) return false;24
String sub = currBottom.substring(index, index + 2);26
String state = currBottom + " " + newBottom + " " + index;28
if (dp.containsKey(state)) return dp.get(state);30
if (map.containsKey(sub)) {31
List<Character> letters = map.get(sub);33
for (char c : letters) {34
if (index == currBottom.length() - 2) {35
if (dfs(newBottom + c, "", 0)) {39
} else if (dfs(currBottom, newBottom + c, index + 1)) {