This problem simply restated is this: given a bunch of strings and a target string, what all combinations from the given string can combine together to form target string with and without repetition.
e.g.
strings: we do what we must because we can
target: wedowhatwemustbecausewecan
output: we do what we must because we can
Approach I took is to remove every longer word from the target until target becomes empty. If targets becomes empty then just return the output. If longer words doesn't lead to a solution then try with shorter words and so on. I am also using memoization to make sure that if the target is already tried then just return, same as backtracking with memoization.
This apporach passed all the testcases except 2, where I am getting timeout.
def recursions(word_map, paswd, output, remember):
flag = 0
if len(paswd) == 0:
return 1
if paswd in remember:
return flag
for char in paswd:
for word in (word_map[char] if char in word_map else []):
if paswd.startswith(word):
output.append(word + " ")
if recursions(word_map, paswd[len(word):], output, remember):
return 1
output.pop()
remember[paswd] = 1
return flag
Please help in providing a hint. Complete solution is here.