Please read the new rule regarding the restriction on the use of AI tools. ×

How to find all the ways to construct a string using dynamic programming memoization?

Revision en1, by SHUVRO.C.DAS, 2021-01-11 13:53:22

The problem statement is, You are given a string and an array of some words. All the words are substring of the given string. You have to find all the ways to construct the string from the words of the array.

Suppose you are given a string "abcdef" and an array={ab,abc,cd,def,abcd}; here only one way to construct the string is ="abc+def"

my code prints all the ways. But it is really inefficient. it prints the same path multiple times if exists. It visits all the nodes. I want suggestions to memoize it so that it doesn't visit the same path if it visited it before. Can someone help me? here is my code:

bool constructstring(string target,vectorv) { if(target.size()==0){ for(int i=0;i<vec.size();i++)cout<<vec[i]<<" "; //prints the construction way cout<<endl; vec.pop_back(); return true; } for(int i=0;i<v.size();i++){ int found=target.find(v[i]); //finds the word is present in the string or not. if(found==0){ // checks the word is at the beginning of the string or not string s; s=target; s.erase(0,v[i].size()); vec.push_back(v[i]); constructstring(s,v); } } vec.pop_back(); return false; }

Tags #c++, #string, #dynamic programing, #memoization

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English SHUVRO.C.DAS 2021-01-11 14:03:15 0 (published)
en4 English SHUVRO.C.DAS 2021-01-11 14:02:40 20 (saved to drafts)
en3 English SHUVRO.C.DAS 2021-01-11 13:57:51 65
en2 English SHUVRO.C.DAS 2021-01-11 13:54:04 668
en1 English SHUVRO.C.DAS 2021-01-11 13:53:22 1354 Initial revision (published)