1. 程式人生 > 實用技巧 >140. 單詞拆分 II

140. 單詞拆分 II

給定一個非空字串 s 和一個包含非空單詞列表的字典 wordDict,在字串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。

說明:

分隔時可以重複使用字典中的單詞。
你可以假設字典中沒有重複的單詞。
示例 1:

輸入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
輸出:
[
"cats and dog",
"cat sand dog"
]
示例 2:

輸入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
輸出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解釋: 注意你可以重複使用字典中的單詞。
示例3:

輸入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
輸出:
[]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/word-break-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        res=[]
        found=[]
        self.dfs(s,0,[],res,wordDict,found)
        
return res def dfs(self,s,start,tmp,res,wordDict,found): if start==len(s): res.append(' '.join(tmp)) return True if start in found: return False find=False for i in range(start+1,len(s)+1): if i in found:
continue t=s[start:i] if t in wordDict: tmp.append(t) if self.dfs(s,i,tmp,res,wordDict,found): find=True tmp.pop() if not find: found.append(start) return find