Word Break II
LeetCode 140 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Backtracking over prefix words; a full path is one sentence.
ನಾನು Word Break II (LeetCode 140) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — String DP / Word Break ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.
Approach
- 1
Dictionary in a set.
- 2
backtrack(start, path): if start == len(s), join the path into a sentence.
- 3
For each end after start, if s[start:end] is a word, append it, recurse from end, then pop.
- 4
Return all collected sentences.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
BacktrackingPythonexponential in the worst case
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
#if prefix exists in dict we should move forward to find the rest
#if cat exists - check if sanddog - sand->dog
#backrack - if cats exists - anddog - and->dog
res=[]
words_set = set(wordDict)
def backtrack(start, path):
if start == len(s):
res.append(" ".join(path))
return
for end in range(start+1,len(s)+1):
prefix = s[start:end]
if prefix in words_set:
path.append(prefix)
backtrack(end,path)
path.pop()
backtrack(0,[])
return res
Word Break II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Word Break II ಹಿಂದಿನ intuition ಏನು?
We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.
Word Break II (LeetCode 140) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Dictionary in a set. 2. backtrack(start, path): if start == len(s), join the path into a sentence. 3. For each end after start, if s[start:end] is a word, append it, recurse from end, then pop. 4. Return all collected sentences.
Word Break II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(2ⁿ) worst case (output can be exponential). Space: O(n) recursion. (Accepted approach: Backtracking.)
Word Break II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Pop after recursing or later sentences inherit stale words. For heavy inputs, memoising sentences per start index avoids rework.