Last active
December 23, 2018 04:26
-
-
Save wszdwp/060913e7c8015e9d6aee7be7f51444dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WordBreakII { | |
// 1. dfs with memo | |
private Map<String, List<String>> memo; | |
public List<String> wordBreak(String s, List<String> wordDict) { | |
List<String> ans = new ArrayList<>(); | |
Set<String> set = new HashSet<>(wordDict); | |
memo = new HashMap<>(); | |
return wordBreak(s, set); | |
} | |
private List<String> wordBreak(String s, Set<String> set) { | |
if (memo.containsKey(s)) return memo.get(s); | |
List<String> ans = new ArrayList<>(); | |
if (set.contains(s)) ans.add(s); | |
for (int j = 1; j < s.length(); j++) { | |
String right = s.substring(j); | |
if (!set.contains(right)) continue; | |
String left = s.substring(0, j); | |
List<String> one = concatAns(wordBreak(left, set), right); | |
ans.addAll(one); | |
} | |
memo.put(s, ans); | |
return ans; | |
} | |
private List<String> concatAns(List<String> cur, String right) { | |
List<String> ans = new ArrayList<>(); | |
for (String prefix : cur) { | |
ans.add(prefix + " " + right); | |
} | |
return ans; | |
} | |
// 2. dfs, TLE | |
public List<String> wordBreak(String s, List<String> wordDict) { | |
List<String> ans = new ArrayList<>(); | |
Set<String> set = new HashSet<>(wordDict); | |
List<String> cur = new ArrayList<>(); | |
memo = new HashMap<>(); | |
dfs(s, 0, set, cur, ans); | |
return ans; | |
} | |
private void dfs(String s, Set<String> set, List<String> cur, List<String> ans) { | |
if (start == s.length()) { | |
ans.add(getStringFromList(cur)); | |
return; | |
} | |
for (int j = start + 1; j <= s.length(); j++) { | |
String sub = s.substring(start, j); | |
if (!set.contains(sub)) continue; | |
cur.add(sub); | |
dfs(s, j, set, cur, ans); | |
cur.remove(cur.size() - 1); | |
} | |
return false; | |
} | |
private String getStringFromList(List<String> cur) { | |
StringBuilder sb = new StringBuilder(); | |
for (String s : cur) sb.append(s + " "); | |
return sb.toString().trim(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment