Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
1 <= s.length <= 3001 <= wordDict.length <= 10001 <= wordDict[i].length <= 20s and wordDict[i] consist of only lowercase English letters.wordDict are unique.In this approach, we will use recursion to break down the problem. The idea is to check if the current prefix of the string can be found in the word dictionary, and if it is, we recursively check the remaining substring. If any path returns true, we know the string can be segmented according to the dictionary.
This method may have overlapping subproblems, which makes it inefficient for larger inputs.
s due to the exponential growth in possible substrings.To optimize the previous recursive solution, we store the result of already processed substrings in a memoization table to avoid recomputation. This approach utilizes dynamic programming concepts to store results of subproblems, thus reducing redundant calculations.
We can further improve the solution by using dynamic programming. The idea is to use a boolean dp array where dp[i] represents whether the substring s[0...i] can be segmented using the dictionary. For each position, we check all possible partitions, updating the dp array based on previously computed results.