📚140. Word Break II

2016-12-22  本文已影响15人  沉睡至夏

题目的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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读