
Problem
Solution
Submissions
Word Break II
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program that returns all possible sentences where each word is a valid dictionary word, given a string and a dictionary of words. 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"]
- Explanation:
We have to break "catsanddog" using dictionary words.
First possibility: "cats" + "and" + "dog" = "cats and dog".
Second possibility: "cat" + "sand" + "dog" = "cat sand dog".
Both combinations use only dictionary words.
Example 2
- Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
- Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
- Explanation:
Multiple ways to break the string using dictionary words.
"pine" + "apple" + "pen" + "apple", "pineapple" + "pen" + "apple", "pine" + "applepen" + "apple".
Constraints
- 1 ≤ s.length ≤ 20
- 1 ≤ wordDict.length ≤ 1000
- 1 ≤ wordDict[i].length ≤ 10
- s and wordDict[i] consist of only lowercase English letters
- Time Complexity: O(2^n) in worst case
- Space Complexity: O(2^n) for storing results
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 dynamic programming with memoization to avoid recomputing subproblems
- For each position in string, try all possible word matches from dictionary
- If a word matches, recursively solve for the remaining substring
- Use backtracking to build all possible sentence combinations
- Memoize results for each starting position to optimize performance
- Base case: empty string returns empty list indicating successful word break