isScramble using dynamic programming cpp leetcode

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representation of s1 = “great”:

great
/ \
gr eat
/ \ / \
g r e at
/ \
a t
To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node “gr” and swap its two children, it produces a scrambled string “rgeat”.

rgeat
/ \
rg eat
/ \ / \
r g e at
/ \
a t
We say that “rgeat” is a scrambled string of “great”.

Similarly, if we continue to swap the children of nodes “eat” and “at”, it produces a scrambled string “rgtae”.

rgtae
/ \
rg tae
/ \ / \
r g ta e
/ \
t a
We say that “rgtae” is a scrambled string of “great”.

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.

[[code]]czoxNjI3OlwiDQpib29sIGlzU2NyYW1ibGUoc3RyaW5nIHMxLCBzdHJpbmcgczIpIHsNCjxzcGFuIHN0eWxlPVwiY29sb3I6ICMzMzk5e1smKiZdfTY2O1wiPi8vIFRoaXMgc29sdXRpb24gaXMgZHAtYmFzZWQuPC9zcGFuPg0KPHNwYW4gc3R5bGU9XCJjb2xvcjogIzMzOTk2NjtcIj4gLy97WyYqJl19IGRwW2ldW2pdW2tdIHJlcHJlc2VudHMgaWYgczEuc3Vic3RyKGksIGkgKyBrKSBpcyBzY3JhbWJsZSBvZiBzMi5zdWJzdHIoaiwgantbJiomXX0gKyBrKTwvc3Bhbj4NCjxzcGFuIHN0eWxlPVwiY29sb3I6ICMzMzk5NjY7XCI+IC8vIFRoZW4gZHBbMF1bMF1bbl0gaXMgd2hhdCB3ZSB7WyYqJl19d2FudCBldmVudHVhbGx5Ljwvc3Bhbj4NCjxzcGFuIHN0eWxlPVwiY29sb3I6ICMzMzk5NjY7XCI+IC8vIERvd24tdG8tdG9wLiBTdGFye1smKiZdfWluZyBmcm9tIGkgPSBqID0gbiAtIDEuIGsgPSAxLjwvc3Bhbj4NCmludCBuID0gczEubGVuZ3RoKCksIGksIGosIGssIGw7DQoNCjx7WyYqJl19c3BhbiBzdHlsZT1cImN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