Leetcode 139. Word Break (python+cpp)

Leetcode 129 Word Break

  • 题目
  • 解法1:recursion (TLE)
  • 解法2:recursion + memorization(bottom up)
  • 解法3:recursion + memorization(top down)
  • 解法3:动态规划
  • 三刷解法
  • 总结
  • follow up

题目

Leetcode 139. Word Break (python+cpp)_第1张图片

解法1:recursion (TLE)

最直观的解法就是用recursion将string不断分成小的部分,但是这样的方法会超时,代码如下:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        # recurrsion 解法,TLE
        def dfs(start):
            if start == len(s):
                return True
            
            for i in range(start+1,len(s)+1):
                if s[start:i] in wordDict and dfs(i):
                    return True
            return False
    
        return dfs(0)

解法2:recursion + memorization(bottom up)

其实上面recursion的解法会对string的某个位置重复计算很多遍,所以可以用一个字典来记录已经做过的位置,避免重复计算,只需要加几行代码即可。
python代码如下:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        def helper(curr):
            if curr == len(s):
                return True
            if curr in memo:
                return memo[curr]
            memo[curr] = False
            for i in range(curr,len(s)+1):
                if s[curr:i] in wordDict and helper(i):
                    memo[curr] = True
                    break
            return memo[curr]
        
        memo = {
   }
        return helper(0)

解法3:recursion + memorization(top down)

class Solution:
    def wordBreak(self, s: str, wordDict: List[str

你可能感兴趣的:(Leetcode,动态规划,leetcode,c++,python,递归法,动态规划)