-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
44 lines (36 loc) · 1.1 KB
/
Solution.cs
File metadata and controls
44 lines (36 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Solution
{
public bool PyramidTransition(string bottom, IList<string> allowed)
{
Dictionary<string, List<char>> map = [];
foreach (string str in allowed)
{
string key = str[..2];
char val = str[2];
map.TryAdd(key, []);
map[key].Add(val);
}
return BuildPyramid("", bottom, map);
}
Dictionary<string, bool> memo = [];
bool BuildPyramid(string cur, string bottom, Dictionary<string, List<char>> map)
{
if (bottom.Length == 1) return true;
if (cur.Length == 0 && memo.TryGetValue(bottom, out bool cached))
return cached;
int i = cur.Length;
if (i == bottom.Length - 1)
{
bool res = BuildPyramid("", cur, map);
memo[bottom] = res;
return res;
}
string key = "" + bottom[i] + bottom[i + 1];
if (!map.ContainsKey(key)) return false;
foreach (char c in map[key])
{
if (BuildPyramid(cur + c, bottom, map)) return true;
}
return false;
}
}