Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
PyramidTransitionMatrix_recursive
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
/* 25 String Pyramids Transition Matrix -- leetcode 756 Given a list of leaf nodes in a pyramid, and a map which indicates what's the possible parent node given a left and right node. Return true if the one of leaf node could turn into the root node, Otherwise, return false. For example: root / \ X X /\ /\ X X X / \/ \/ \ A B C D Map: left: A | B | C | D right--------------------------------- A B |A or C| D | A B D |B or C| A | C B D Note:1. If left child is B, right child is A, the parent node could be B or C Given leaf input of "ABCD", output true. */ #include <vector> #include <iostream> #include <map> #include <set> #include <assert.h> using namespace std; class Pyramid{ map<string, set<char>> m; // all potential mapping string to a char, set<char> search(string bottom) { if(m.count(bottom)) return m[bottom]; int n = bottom.size(); if(n ==2) return {}; // should return result string s1 = bottom.substr(0,n-1); string s2 = bottom.substr(1); set<char> r1 = search(s1); set<char> r2 = search(s2); set<char> res; for(char x: r1){ for(char y: r2) { string xy = "xy"; xy[0] = x; xy[1] = y; set<char> r3 = search(xy); res.insert(r3.begin(), r3.end()); } } if(res.size()) m[bottom] = res; return res; } public: Pyramid(vector<string>& lines){ for(auto s: lines){ string rest = s.substr(2); for(char c: rest) m[s.substr(0,2)].insert(c); } //cout<< "map.size() = " << m.size() << endl; } bool check(string bottom){ if(bottom.size()<2) return false; set<char> res = search(bottom); //cout << "res.size=" << res.size() << endl; return res.size()>0; } }; int main(){ vector<string> lines = {"AAAC", "ABCD", "ACD", "ADB", "BAB", "BBC", "BCA", "BDCD", "CAA", "CBC", "CCD", "CDB", "DABC", "DBD", "DCA", "DDC"}; Pyramid p(lines); string bottom = "AACD"; bool res = p.check(bottom); cout << ( res==true? "True" : "False") << endl; assert(p.check("ABCD")); assert(p.check("AACD")); assert(p.check("AAAA")); assert(p.check("CCCC")); assert(p.check("DDDD")); return 0; }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.93 sec, absolute running time: 0.07 sec, cpu time: 0.02 sec, memory peak: 3 Mb, absolute service time: 1,03 sec
edit mode
|
history
|
discussion
map.size() = 8 res.size=1 True