To solve this problem, we need to generate all possible sentences by adding spaces to a given string such that each word in the sentence is a valid word from the provided dictionary. We use a backtracking approach combined with memoization to efficiently explore all valid segmentations and avoid redundant calculations.
Approach
- Memoization: We use memoization to store results of subproblems (i.e., all valid sentences for a substring) to avoid recomputing them multiple times.
- Backtracking: We recursively break down the string into valid prefixes (from the dictionary) and then solve for the remaining suffix. For each valid prefix, we combine it with all valid sentences of the suffix to form complete sentences.
- Base Case: When the remaining string is empty, we return an empty string as the base case (indicating the end of a valid sentence).
Solution Code
from functools import lru_cache
from typing import List
def wordBreak(s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict)
@lru_cache(maxsize=None)
def backtrack(remaining: str) -> List[str]:
if not remaining:
return [""]
sentences = []
for i in range(1, len(remaining) + 1):
prefix = remaining[:i]
if prefix in wordSet:
suffix_sentences = backtrack(remaining[i:])
for suffix in suffix_sentences:
if suffix:
sentences.append(f"{prefix} {suffix}")
else:
sentences.append(prefix)
return sentences
return backtrack(s)
Explanation
- Memoization: The
@lru_cachedecorator is applied to thebacktrackfunction to cache results of subproblems. This ensures that each substring is processed only once. - Backtrack Function: The
backtrackfunction takes a remaining substring and returns all valid sentences for that substring.- Base Case: If the remaining substring is empty, return
[""](since we've reached the end of a valid sentence). - Recursive Case: For each possible prefix of the remaining substring:
- If the prefix is a valid word (present in the dictionary), recursively find all valid sentences for the suffix (remaining substring after the prefix).
- Combine the prefix with each valid suffix sentence: if the suffix is non-empty, add a space between the prefix and suffix; otherwise, add just the prefix.
- Base Case: If the remaining substring is empty, return
- Main Function: The main function converts the dictionary into a set (for O(1) lookups) and calls the
backtrackfunction with the original string to get all valid sentences.
This approach efficiently explores all valid segmentations using backtracking and memoization, ensuring optimal performance for the given problem constraints. The solution handles all edge cases, including reusing dictionary words multiple times and generating all possible valid sentences.
作者声明:本文包含人工智能生成内容。