??140. Word Break II

題目的tag是DP,看了別人答案,確實用DFS解更好一些。

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        return helper(s, new HashMap<String, List<String>>(), wordDict);
    }
    
    public List<String> helper(String s, Map<String, List<String>> map, Set<String> wordDict) {
        if(map.containsKey(s)) {
            return map.get(s);
        }
        List<String> list = new LinkedList<String>();
        if(s.length()==0) {
            list.add("");
            return list;
        }
        
        for(String word : wordDict) {
            if(s.startsWith(word)) {
                List<String> result = helper(s.substring(word.length()), map, wordDict);
                for(String part : result) {
                    list.add(word + (part.length()==0? "":" ") + part);
                }
            }
        }
        
        map.put(s, list);
        return list;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容