140. 单词拆分 II

https://leetcode-cn.com/problems/word-break-ii/

 

 

 

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        # 本题就是加上剪枝的回溯算法
        # record的关键: 
        # 1. record初始全设为1
        # 2. 当s[i:]后续无法为res中增加答案时,将其设为False
        # 3. 在递归的入口处使用 record[lenS]

        if not s or not wordDict: return []
        def dfs(curRes,curString,lenS):
            cur_num = len(res)
            if lenS == l:
                res.append(' '.join(curRes))
                return 
            for i in range(min(len(curString),maxl)):
                if curString[:i+1] in wordDict and record[lenS]:
                    dfs(curRes+[curString[:i+1]],curString[i+1:],lenS+(i+1))
            record[lenS] = 1 if len(res) > cur_num else 0
        maxl = max(list(map(len,wordDict)))
        l = len(s)
        record = [True]*(l+1)
        res = []
        dfs([],s,0)
        return res

  

posted @ 2020-12-21 10:04  ChevisZhang  阅读(84)  评论(0编辑  收藏  举报