Word Break II

Description

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given s = "catsanddog", dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

Hint

Train of Thought

Using DFS directly will lead to TLE, so I just used HashMap to save the previous results to prune duplicated branches, as the following:

http://www.cnblogs.com/yuzhangcmu/p/4037299.html 解答1 (dfs): 让我们来继续切切切吧!

本题与上一题Word Break思路类似,但是一个是DP,一个是DFS。 让我们来回顾一下DP与DFS的区别: DP是Bottom-up 而DFS是TOP-DOWN.

在本题的DFS中,我们这样定义: 用刀在字符串中切一刀。左边是i个字符,右边是len-i个字符。 i: 1- len 如果: 左边是字典里的词,右边是可以wordbreak的,那么把左边的字符串加到右边算出来的List中,生成新的list返回。

  1. Base case: 当输入字符串为空的时候,应该给出一个空解。这个很重要,否则这个递归是不能运行的。
  2. 递归的时候,i应该从1开始递归,因为我们要把这个问题分解为2个部分,如果你左边给0,那就是死循环。

记忆: 为了加快DFS的速度,我们应该添加记忆,也就是说,算过的字符串不要再重复计算。举例子: apple n feng app len feng 如果存在以上2种划分,那么feng这个字符串会被反复计算,在这里至少计算了2次。我们使用一个Hashmap把对应字符串的解记下来,这样就能避免重复的计算。 否则这一道题目会超时。

Code

//forloop字典里面的词, 看是否存在在String里,这样就不用一个一个字符的检验
public List<String> wordBreak(String s, Set<String> wordDict) {
    return DFS(s, wordDict, new HashMap<String, LinkedList<String>>());
}       

// DFS function returns an array including all substrings derived from s.
List<String> DFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>>map) {
    if (map.containsKey(s)) 
        return map.get(s);

    LinkedList<String>res = new LinkedList<String>();     
    if (s.length() == 0) {
        res.add("");
        return res;
    }               
    for (String word : wordDict) {
        if (s.startsWith(word)) {
            List<String>sublist = DFS(s.substring(word.length()), wordDict, map);
            for (String sub : sublist) 
                res.add(word + (sub.isEmpty() ? "" : " ") + sub);               
        }
    }       
    map.put(s, res);
    return res;
}

Complexity

results matching ""

    No results matching ""