题目描述
思路分析
线性dp+暴搜
f
[
i
]
:
[
i
,
n
]
f[i]:[i,n]
f[i]:[i,n]能否被拆分
[
i
,
j
]
的
h
a
s
h
存
在
a
n
d
f
[
j
+
1
]
=
t
r
u
e
t
h
e
n
f
[
i
]
=
t
r
u
e
l
[i,j]的hash存在\ and\ f[j+1]=true\ then\ f[i]=truel
[i,j]的hash存在 and f[j+1]=true then f[i]=truel
代码实现
class Solution {
public:
vector<bool> f;
unordered_set<string> hash;
vector<string> ans;
int n;
vector<string> wordBreak(string s, vector<string>& wordDict) {
n=s.size();
f.resize(n+1);
for(auto t:wordDict) hash.insert(t);
f[n]=true;
for(int i=n-1;~i;i--){
for(int j=i;j<n;j++){
if(hash.count(s.substr(i,j-i+1))&&f[j+1]) f[i]=true;
}
}
dfs(s,0,"");
return ans;
}
void dfs(string &s,int u,string path){
if(u==n){
path.pop_back();
ans.push_back(path);
return;
}
for(int i=u;i<n;i++){
if(hash.count(s.substr(u,i-u+1))&&f[i+1]){
dfs(s,i+1,path+s.substr(u,i-u+1)+" ");
}
}
}
};