Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
class Solution {
public:
void printRes(int n,int* matrix,string s,vector<string>& ret,int j,stack<string> st)
{
if(j == -1){
string str = "";
while(!st.empty()){
str+= st.top()+" ";
st.pop();
}
if(str!="") str.erase(str.size()-1,1);
ret.push_back(str);
return;
}
for(int i = 0;i<n;i++)
{
if(matrix[i*n+j] == 2){
st.push(s.substr(i,j-i+1));
printRes(n,matrix,s,ret,i-1,st);
st.pop();
}
}
}
vector<string> wordBreak(string s, unordered_set<string> &dict) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<string> ret;
int n = s.length();
int matrix[n][n];
for(int i = 0;i<n;i++)
memset(matrix[i],0,n*sizeof(int));
for(int l = 1;l<=n;l++)
{
for(int i = 0;i<n-l+1;i++)
{
int j = i+l-1;
if(dict.find(s.substr(i,l)) != dict.end()) {
matrix[i][j] = 2;
continue;
}
for(int k = i;k<j;k++)
{
if(matrix[i][k] != 0 && matrix[k+1][j] != 0) matrix[i][j] = 1;
}
}
}
stack<string> st;
printRes(n,(int *)matrix,s,ret,n-1,st);
return ret;
}
};
100 ms