[LeetCode] 0140. Word Break ii

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link

Table of contents

Hard

 


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.
  • Input is generated in a way that the length of the answer doesn't exceed 105.

Python

				
					# time complexity: O(2^n) # space complexity: O(2^n) from typing import List class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: word_set = set(wordDict) memoization = {} return self._dfs(s, word_set, memoization) def _dfs(self, remainingStr: str, wordSet: set, memoization: dict) -> List[str]: if remainingStr in memoization: return memoization[remainingStr] if not remainingStr: return [""] results = [] for i in range(1, len(remainingStr) + 1): currentWord = remainingStr[:i] if currentWord in wordSet: for nextWord in self. _dfs(remainingStr[i:], wordSet, memoization): results.append( currentWord + (" " if nextWord else "") + nextWord) memoization[remainingStr] = results return results s = "catsanddog" wordDict = ["cat" , "cats", "and", "sand", "dog"] print(Solution().wordBreak(s, wordDict))
				
			
en_USEnglish