140. Word Break II
class Solution { public List<String> wordBreak(String s, List<String> wordDict) { Map<String,List<String>> map=new HashMap<String,List<String>>(); wordBreak(s, map, wordDict); return map.get(s); } private void wordBreak(String s, Map<String,List<String>> map, List<String> wordDict){ if(map.containsKey(s)) return; List<String> list=new ArrayList<String>(); if(s.length()==0) { list.add(""); map.put(s,list); return; } for(String w:wordDict) if(s.startsWith(w)) { String str=s.substring(w.length()); wordBreak(str,map,wordDict); List<String> l=map.get(str); for(String sentence:l) list.add(w+(sentence.length()!=0?" ":"")+sentence); } map.put(s,list); } }