[LeeCode] 139. Word Break (递归+记忆数组 / dp)

139. Word Break

Medium

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3:

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

 

方法1:递归+记忆数组

我们每次需要查找某个单词是否在wordDict里面,因为给的是一个list,每次查找的话,需要O(n),所以为了提高效率,把wordDict变成一个hashset,这样查找起来的时间复杂度为O(1)。这个题怎么做呢,我们需要找到所有可能的组合情况,考虑使用递归去实现,比如第一个例子,s="leetcode",我们首先去判断第一个字母“l”是否在wordDict里面,如果在的话,我们就直接进入递归函数check,去检查去除“l”的剩下字母是否在wordDict里面;如果"l"不在wordDict里面,我们就判断"le"是否在wordDict里面,然后同样进行上述步骤,如果当连“leetcode”都没在wordDict里面的话,说明这个s不符合条件,返回false。按照这个思路去写的话,写出来的代码是下面这样的:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        word_set = collections.defaultdict(int)
        wordDict = set(wordDict)
        def check(start):
            if start >= len(s):
                return True
            for i in range(start + 1, len(s) + 1):
                if s[start:i] in wordDict and check(i):
                    return True
            return False
        return check(0)

这样写的话,提交的话会超时,因为我们在递归的过程中进行了很多次的重复计算。比如当我们先拆分s为“l”和“eetcode”,我们经过一遍递归后,知道“eetcode”无论如何分,结果都是false,所有我们在将字符分为“le”和“etcode”的时候,就知道“etcode”一定不会符合条件,这样分最后结果一定是false,所以此时我们就没有必要接着递归下去,直接返回false就行了。所以这个过程我们减少了不必要的计算。我们使用记忆数组memo来记录中间的计算过程,这样在用到的时候我们直接调用就行了,不需要进行不必要迭代过程,代码修改后变为下面这样:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        word_set = collections.defaultdict(int)
        wordDict = set(wordDict)
        memo = [-1] * len(s)
        def check(start):
            if start >= len(s):
                return True
            if memo[start] != -1:
                return memo[start]
            for i in range(start + 1, len(s) + 1):
                if s[start:i] in wordDict and check(i):
                    memo[start] = True
                    return True
            memo[start] = False
            return False
        return check(0)

方法2: 动态规划

dp[i]为s[0:i)是否满足可分,也就是分成的单词可以在wordDict里面找到。可分置为True,不可分置为False

我们将s[0,i)分为两部分,s[0,j)和s[j,i),如果dp[j]=True并且s[j,i)能够在wordDict里面找到,则将dp[i]置为True,同时break。如果无论j怎么分,都不能满足要求,dp[i]=False

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        wordDict = set(wordDict)
        dp = [False] * (len(s) + 1)

        dp[0] = True
        for i in range(len(s) + 1):
            for j in range(0, i):
                if dp[j]:
                    if s[j:i] in wordDict:
                        dp[i] = True
                        break
        return dp[len(s)]

总结:

记忆化数组+递归的方法是从上到下,也就是说由整体到最小的部分的

动态规划是从下向上,也就是说从最小的计算开始,最后拼成一个整体

在涉及到子串或者子数组问题的时候,考虑使用动态规划

参考 https://blog.csdn.net/zjxxyz123/article/details/80147546

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值