


The same word from a dictionary can be used as many times as possible to make sentences.
The first line contains an integer value ‘n’ which denotes the size of the dictionary.
Next ‘n’ lines contains a non-empty string denoting words of dictionary.
Next (n+1)th line contains a non-empty string 's'.
The output contains each possible sentence on a new line. If no such string can be formed then output is '-1'.
You don’t need to print anything. Just implement the given function.
We need to keep exploring the given string from current position ‘i’ to until we wouldn’t find a position such that substring ‘i’ to ‘j’ exists in the dictionary.
The algorithm looks like:
While exploring all possibilities, we are also going to store whatever solution we got till now for a sentence so that we will be able to avoid redundant function calls.
unordered_map<int,vector<string>> dpdp[index] contains a list of all the valid sentences that can be formed with a substring of the sentence from “index” to “sentence.size()-1”.
The idea is to use Trie data structure.
A trie is a tree-like data structure whose nodes store the letters of an alphabet. By structuring the nodes in a particular way, words and strings can be retrieved from the structure by traversing down a branch path of the tree.
Using trie will help us to save time and space.
Algorithm: