Leetcode - Word Break II

My code:

public class Solution {
    public List wordBreak(String s, Set wordDict) {
        return helper(s, new HashMap>(), wordDict);
    }
    
    private List helper(String s, Map> map, Set wordDict) {
        if (map.containsKey(s)) {
            return map.get(s);
        }
        List list = new LinkedList();
        if (s.length() == 0) {
            list.add("");
            return list;
        }
        
        for (String word : wordDict) {
            if (s.startsWith(word)) {
                List 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

你可能感兴趣的:(Leetcode - Word Break II)