leetcode140.单词拆分 II

1.题目描述

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

2.解题思路

一开始使用正向递归,发现时间复杂度过不去,但是还是上一下代码为了以后复习。

class Solution(object):
    def dfs(self, s, start, wordDict, out, res):
        if start == len(s):
            tmp = " ".join(string for string in out)
            res.append(tmp)
            return 
        for i in range(start,len(s)):
            if s[start:i+1] in wordDict:
                out.append(s[start:i+1])
                self.dfs(s, i+1, wordDict, out, res)
                out.pop(-1)
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        res=[]
        out=[]
        self.dfs(s, 0, wordDict, out, res)
        return res

实际上,要利用记忆化的dfs,思路和leetcode494leetcode329一致,是反向递归(先出来后面步骤的结果)

要避免重复计算,如何避免呢,还是看上面的分析,如果当s变成 "sanddog"的时候,那么此时我们知道其可以拆分成sand和dog,当某个时候如果我们又遇到了这个 "sanddog"的时候,要将这个中间结果保存起来,由于我们必须要同时保存s和其所有的拆分的字符串,那么可以使用一个HashMap,来建立二者之间的映射,那么在递归函数中,我们首先检测当前s是否已经有映射,有的话直接返回即可,如果s为空了,我们如何处理呢,题目中说了给定的s不会为空,但是我们递归函数处理时s是会变空的,这时候我们是直接返回空集吗,这里有个小trick,我们其实放一个“#”返回,为啥要这么做呢?我们观察题目中的Output,发现单词之间是有空格,而最后一个单词后面没有空格,所以这个空字符串就起到了标记当前单词是最后一个,那么我们就不要再加空格了。

3.代码实现

class Solution(object):
    def dfs(self, s, wordDict, cache):
        if s in cache:
            return cache[s]
        if not s:
            return "#"
        res=[]
        for word in wordDict:
            if s[0:len(word)] != word:
                continue
            rem = self.dfs(s[len(word):], wordDict, cache)
            for string in rem:
                if string == "#":
                    res.append(word+"")
                else:
                    res.append(word+" "+string)
        cache[s] = res[:]
        return res[:]
        
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        cache = dict()
        return self.dfs(s, wordDict, cache)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值