内容中心

2026年评价高的天津红外压片机实力厂家怎么选?

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

  1. Memoization: We use memoization to store results of subproblems (i.e., all valid sentences for a substring) to avoid recomputing them multiple times.
  2. 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.
  3. 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

  1. Memoization: The @lru_cache decorator is applied to the backtrack function to cache results of subproblems. This ensures that each substring is processed only once.
  2. Backtrack Function: The backtrack function 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.
  3. Main Function: The main function converts the dictionary into a set (for O(1) lookups) and calls the backtrack function 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.



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?