dp数组为布尔值的题目。排列问题所以要先遍历背包。 dp[i]为在字符串s的[0,i]子串,是否符合题目要求,即为字典内词的组合。 递推公式为:dp[i]在[j,i]子串为字典子串,且dp[i]为true时,dp[i]取true。 最后返回dp数组的最后一个元素。
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length()+1];
Set<String> myset = new HashSet<String>(wordDict);
for(int i=0; i<dp.length; i++) {
dp[i] = false;
}
dp[0] = true;
for(int i=1; i<=s.length(); i++) {
for(int j=0; j<i; j++) {
//word j-i
String word = s.substring(j,i);
if(myset.contains(word) && dp[j]) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}