
Problem
Solution
Submissions
Word Break II
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program that given a string `s` and a dictionary of strings `wordDict`, returns all possible sentences that can be formed by breaking `s` into a sequence of one or more dictionary words, separated by spaces. The same word from the dictionary can be used multiple times. Return the sentences in any order.
Example 1
- Input: s = "catsanddog",
wordDict = ["cat", "cats", "and", "sand", "dog"] - Output: ["cats and dog", "cat sand dog"]
- Explanation: One possible breaking is "cats" + "and" + "dog" = "cats and dog". Another possible breaking is "cat" + "sand" + "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: There are three ways to break down "pineapplepenapple" into dictionary words.
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 strings in wordDict are unique
- Time Complexity: O(2^n), where n is the length of the string s
- Space Complexity: O(n * k), where k is the number of valid sentences
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a combination of backtracking and dynamic programming to solve this problem
- Create a memoization map to store intermediate results, which can significantly improve performance
- Use recursion to explore all possible ways to break the string
- For each position in the string, check if there is a valid word in the dictionary that starts at that position
- If a valid word is found, recursively process the remaining part of the string
- Use a HashSet to quickly check if a word exists in the dictionary
- Build the sentences incrementally as you find valid word breaks