Leetcode 140. Word Break II

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

题意:139的followup,求出所有的break方案。

思路:
第一想到的还是深度优先搜索,在139的基础上用一个String类型的path记录当前的break方案,再用一个List<String> res存储找到的所有path。

public List<String> wordBreak(String s, List<String> wordDict) {
    List<String> res = new ArrayList<>();
    if (s == null || s.length() == 0) {
        return res;
    }

    HashSet<String> set = new HashSet<>();
    for (String word : wordDict) {
        set.add(word);
    }

    dfs(s, 0, set, res, "");

    return res;
}

private void dfs(String s, int start, HashSet<String> set, List<String> res, String path) {
    if (start == s.length()) {
        res.add(path.trim());
        return;
    }

    for (int i = start + 1; i <= s.length(); i++) {
        String str = s.substring(start, i);
        if (!set.contains(str)) {
            continue;
        }
        dfs(s, i, set, res, path + str + " ");
    }
}

提交以后还是会超时,下面是一个记忆化搜索的解法,通过hashmap来记录后面子串已经搜索过的组合,来避免重复搜索。

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;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/7a703d5f4830
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞