leetcode140. 单词拆分 II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/88743869

给定一个非空字符串 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”]
输出:
[]

先判断能否拆分,再dfs得出结果:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        # 先判断能否拆分,再回溯生成所有结果
        dp = [False] * (1+len(s))
        dp[0], self.res = True, []
        for i in range(1, len(s)+1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i] = True
                    break
        if dp[-1]:
            self.dfs(s, wordDict, '')
        return self.res
    
    def dfs(self, s, words, tmp):
        if not s:
            self.res.append(tmp[:-1])
        for word in words:
            if s.startswith(word):
                self.dfs(s[len(word):], words, tmp+word+' ')

用dp的结果简化运算:

class Solution:
    def wordBreak(self, s: str, wordDict):
        # 先判断能否拆分,再回溯生成所有结果
        self.dp = [False] * (1 + len(s))
        self.dp[0], self.res = True, []
        for i in range(1, len(s) + 1):
            for j in range(i):
                if self.dp[j] and s[j:i] in wordDict:
                    self.dp[i] = True
                    break
        if self.dp[-1]:
            self.dfs(s, wordDict, '', 0)
        return self.res

    def dfs(self, s, words, tmp, i):
        if i == len(s):
            self.res.append(tmp[:-1])
        for j in range(1, len(s[i:])+1):
            if self.dp[i+j] and s[i:i+j] in words:
                self.dfs(s, words, tmp+s[i:i+j]+' ', i+j)

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/88743869
今日推荐