140. Word Break II (Hard)

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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"].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

Solution 1: DFS + HashMap O(n * 2^n) 或者 O(n * len(wordDict) ^ len(s / minWordLenInDict)); O(n)

During DFS, use a HashMap. The key is the substring of input string which appears in the dict and the value is the possible sentences of the substring.
“aaaaaa”, [“a”, “aa”, “aaa”, “aaaa”, “aaaaa”, “aaaaa”]
“aaaaab”, [“a”, “aa”, “aaa”, “aaaa”, “aaaaa”, “aaaaa”]

    public List<String> wordBreak(String s, List<String> wordDict) {
        return dfs(s, new HashSet(wordDict), new HashMap<>());
    }

    // dfs function returns an array including all substrings derived from s.
    List<String> dfs(String s, Set<String> wordDict, Map<String, List<String>> map) {
        if (map.containsKey(s)) { //Base case 1:
            return map.get(s);
        }

        List<String> res = new ArrayList<>();
        if (s.length() == 0) { //Base case 2:
            res.add("");
            return res; //可以不写,但是会变慢,因为没剪枝。
        }

        for (String word : wordDict) {
            if (s.startsWith(word)) { //important!
                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;
    }

Solution 2:

results matching ""

    No results matching ""