lc-140


/**
Given a string s and a dictionary of strings wordDict, add spaces in s to
construct a sentence where each word is a valid dictionary word. Return all such
possible sentences in any order.

 Note that the same word in the dictionary may be reused multiple times in the
segmentation.


 Example 1:


Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
Output: ["cats and dog","cat sand dog"]


 Example 2:


Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine",
"pineapple"]
Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
Explanation: Note that you are allowed to reuse a dictionary word.


 Example 3:


Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: []



 Constraints:


 1 <= s.length <= 20
 1 <= wordDict.length <= 1000
 1 <= wordDict[i].length <= 10
 s and wordDict[i] consist of only lowercase English letters.
 All the strings of wordDict are unique.

 Related Topics字典树 | 记忆化搜索 | 哈希表 | 字符串 | 动态规划 | 回溯

 👍 650, 👎 0

*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        if (s == null || s.length() == 0 || wordDict == null || wordDict.size() == 0) {
            return new ArrayList<>();
        }
        Map<Integer, List<String>> resultMap = new HashMap<>();
        return wordBreakInner(s, s.length() - 1, resultMap, wordDict);
    }

    private List<String> wordBreakInner(String s, int index, Map<Integer, List<String>> resultMap, List<String> wordDict) {
        if (resultMap.containsKey(index)) {
            return resultMap.get(index);
        }

        List<String> result = new ArrayList<>();

        for (String dict : wordDict) {
            if (index + 1 < dict.length()) {
                continue;
            }

            if (dict.equals(s.substring(index - dict.length() + 1, index + 1))) {
                if (index + 1 == dict.length()) {
                    result.add(dict);
                } else {
                    List<String> subResult = wordBreakInner(s, index - dict.length(), resultMap, wordDict);

                    if (subResult.size() > 0) {
                        for (String sub : subResult) {
                            result.add(sub + " " + dict);
                        }
                    }
                }
            }
        }

        resultMap.put(index, result);

        return result;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !