140. Word Break II 发表于 2022-01-30 DFS1234567891011121314151617181920212223242526class Solution { public List<String> wordBreak(String s, List<String> wordDict) { Set<String> wordSet = new HashSet<>(wordDict); List<String> sentenceList = new ArrayList<>(); List<String> wordList = new ArrayList<>(); backtrack(sentenceList, wordList, s, wordSet, 0); return sentenceList; } private void backtrack(List<String> sentenceList, List<String> wordList, String s, Set<String> wordSet, int startIndex) { if (startIndex == s.length()) { sentenceList.add(String.join(" ", wordList)); return; } for (int endIndex = startIndex; endIndex < s.length(); endIndex++) { // word: s[startIndex, endIndex] String word = s.substring(startIndex, endIndex + 1); if (wordSet.contains(word)) { wordList.add(word); backtrack(sentenceList, wordList, s, wordSet, endIndex + 1); wordList.remove(wordList.size() - 1); } } }} Backtracking + Cache1234567891011121314151617181920212223242526272829303132333435class Solution { public List<String> wordBreak(String s, List<String> wordDict) { Set<String> wordSet = new HashSet<>(wordDict); Set<Integer> cannotBreakStartIndexCache = new HashSet<>(); List<String> sentenceList = new ArrayList<>(); List<String> wordList = new ArrayList<>(); backtrack(sentenceList, wordList, s, wordSet, 0, cannotBreakStartIndexCache); return sentenceList; } private void backtrack(List<String> sentenceList, List<String> wordList, String s, Set<String> wordSet, int startIndex, Set<Integer> cannotBreakStartIndexCache) { if (cannotBreakStartIndexCache.contains(startIndex)) { return; } if (startIndex == s.length()) { sentenceList.add(String.join(" ", wordList)); return; } int sentenceListSize = sentenceList.size(); for (int endIndex = startIndex; endIndex < s.length(); endIndex++) { // word: s[startIndex, endIndex] String word = s.substring(startIndex, endIndex + 1); if (wordSet.contains(word)) { wordList.add(word); backtrack(sentenceList, wordList, s, wordSet, endIndex + 1, cannotBreakStartIndexCache); wordList.remove(wordList.size() - 1); } } if (sentenceListSize == sentenceList.size()) { cannotBreakStartIndexCache.add(startIndex); } }} Reference140. Word Break II