Word Break II
import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class WordBreakII { // Memoization map to store results for substrings to avoid recomputation. // Key: starting index of the s...
This program solves the Word Break II problem, which involves segmenting a given string into a space-separated sequence of one or more dictionary words. It returns all possible valid segmentations. This problem is a clas...
The `wordBreak` method uses a recursive backtracking approach with memoization to find all possible ways to segment a string `s` into words from a given dictionary `wordDict`. The `backtrack` helper function explores all possible splits. For each substring starting at `start`, it checks if it's a valid word. If it is, it recursively calls itself for the remainder of the string. The results from the recursive calls are combined with the current word. Memoization (`memo` map) is crucial to store the results for substrings that have already been processed, preventing redundant computations and significantly improving performance. The time complexity, with memoization, is roughly O(n^3) in the worst case (where n is the length of the string), due to substring operations and the number of possible segmentations. The space complexity is O(n^2) in the worst case for storing results in the memoization map and the recursion stack. Edge cases include an empty input string or an empty dictionary, which are handled. The correctness relies on the exhaustive exploration of all valid word combinations and the guarantee that if a substring can be segmented, all its valid segmentations will be found and combined.
function wordBreak(s, wordDict): memo = empty map dict = convert wordDict to a set return backtrack(s, dict, 0, memo) function backtrack(s, dict, start, memo): if start is in memo: return memo[start] results = empty list...