1, Recursion + Memoization 时间: O(n^2) 空间: O(n^2) 是吗。。?
存储之前找过的结果
2, DP 时间: O(n^2) 空间: O(n^2)
1,result的array怎么建?(type? index的含义? size?) -》true or false的,直接建个boolean, i表示substring的length
2,changing condition?
DP1: 要对之前的结果loop一遍
DP2:改进-》没有必要从0开始loop,先求出字典中最长word的长度
3,initial condition? -》 boolean[0] = true;
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, givens =
"leetcode"
,
dict =
["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
// We just need to keep track of those indexes that we have already computed and the result is false
HashSet<Integer> memo = new HashSet<Integer>();
return dfs(s, dict, 0, memo);
}
public boolean dfs(String s, Set<String> hs, int i, HashSet<Integer> memo) {
if(hs.contains(s.substring(i))) return true;
// if we have already computed the result for this substring we just return the answer
if(memo.contains(i)) return false;
for(int j = i+1; j < s.length(); j++){
if(hs.contains(s.substring(i, j))){
if (dfs(s,hs,j,memo)) return true;
}
}
//we just store the results for substrings which result is false
memo.add(i);
return false;
}
}
//DP1
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) return false;
boolean[] res = new boolean[s.length() + 1];
res[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (res[j] && dict.contains(s.substring(j, i))) {
res[i] = true;
break;
}
}
}
return res[s.length()];
}
}
//DP1改进:存储max word length in the dictionary
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if (s == null || s.length() == 0) return false;
boolean[] res = new boolean[s.length() + 1];
res[0] = true;
int maxLen = maxLength(dict);
for (int i = 1; i <= s.length(); i++) {
int j = i - maxLen > 0 ? i-maxLen : 0;
for (; j < i; j++) {
if (res[j] && dict.contains(s.substring(j, i))) {
res[i] = true;
break;
}
}
}
return res[s.length()];
}
public int maxLength(Set<String> dict) {
int max = 0;
for (String w : dict){
max = Math.max(w.length(), max);
}
return max;
}
}