dfs 求解

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @param dic string字符串一维数组 
# @return bool布尔型
#
class Solution:
    def wordDiv(self , s: str, dic: List[str]) -> bool:
        # write code here
        def dfs(idx):
            if idx >= len(s):
                return True
            for i in range(idx, len(s)):
                c = s[idx: i + 1]
                if c in dic:
                    if dfs(i + 1):
                        return True
            return False
        return dfs(0)

动态规划求解

class Solution:
    def wordDiv(self , s: str, dic: List[str]) -> bool:
        # write code here
        dp = [False for _ in range(len(s) + 1)]
        dp[0] = True
        for i in range(1, len(s) + 1):
            for j in range(i):
                dp[i] = dp[j] and s[j:i] in dic
                if dp[i]:
                    break
        return dp[-1]