140.word-break-ii.java 924 B

1234567891011121314151617181920212223242526272829
  1. import java.util.*;
  2. class Solution {
  3. public List<String> wordBreak(String s, List<String> wordDict) {
  4. HashMap<String, List<String>> map = new HashMap<>();
  5. return dfs(s, wordDict, map);
  6. }
  7. private List<String> dfs(String s, List<String> wordDict, HashMap<String, List<String>> map) {
  8. List<String> res;
  9. if ((res = map.get(s)) != null) return res;
  10. res = new ArrayList<>();
  11. if (s.equals("")) {
  12. res.add("");
  13. return res;
  14. }
  15. for (String word : wordDict) {
  16. if (s.startsWith(word)) {
  17. List<String> list = dfs(s.substring(word.length()), wordDict, map);
  18. for (String suffix : list) {
  19. if (suffix.equals("")) res.add(word);
  20. else res.add(word + " " + suffix);
  21. }
  22. }
  23. }
  24. map.put(s, res);
  25. return res;
  26. }
  27. }