Leetcode - Word Break II

My code:

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
        return helper(s, new HashMap<String, List<String>>(), wordDict);
    }
    
    private 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> ret = helper(s.substring(word.length()), map, wordDict);
                for (String part : ret) {
                    list.add(word + (part.length() == 0 ? "" : " ") + part);
                }
            }
        }
        
        map.put(s, list);
        return list;
    }
}

看了答案写出来的。

其实思路很简单。就是dfs + memory cache
reference:
https://discuss.leetcode.com/topic/27855/my-concise-java-solution-based-on-memorized-dfs/3

time complexity:
O(len(wordDict) ^ len(s / minWordLenInDict))

然后 BFS的做法不知道怎么做。

Anyway, Good luck, Richardo! -- 09/06/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容