Lets say you have a string: abcde
And a set of strings: ab, cde, abcd, a, bcd, cd
You want to find all possible concatenations from the set that form the string.
You can use recursion to traverse through all possible concatenations from the set, but how would you return only those that satisfy the solution?
The possible combinations:
ab - cde - yes
ab - cd - no
abcd - no
a - bcd - no
ab - cd - no
You can build a tree from the traverse and then extract the paths that complete. Is there a way without using a tree?
I am implementing this in Python but feel free to answer in any language.
One possibility is to structure the search as a generator. In python, it might look like this:
Note that I have assumed that the elements from the set can occur more than once in the string. If that is inappropriate, replace
fragmentsbyfragments - {frag}in the recursive call.You can get all elements by just gathering all the results from the generator into a list:
This produces:
You could also accumulate all the results into a list as the search proceeds.