[leetcode]Word Break II @ Python


原題地址:https://oj.leetcode.com/problems/word-break-ii/

題意:

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

解題思路:這道題不只像word break那樣判斷是否可以分割,而且要找到所有的分割方式,那么我們就要考慮dfs了。不過直接用dfs解題是不行的,為什么?因為決策樹太大,如果全部遍歷一遍,時間復雜度太高,無法通過oj。那么我們需要剪枝,如何來剪枝呢?使用word break題中的動態規划的結果,在dfs之前,先判定字符串是否可以被分割,如果不能被分割,直接跳過這一枝。實際上這道題是dp+dfs。

代碼:

class Solution:
    # @param s, a string
    # @param dict, a set of string
    # @return a list of strings
    def check(self, s, dict):
        dp = [False for i in range(len(s)+1)]
        dp[0] = True
        for i in range(1, len(s)+1):
            for k in range(0, i):
                if dp[k] and s[k:i] in dict:
                    dp[i] = True
        return dp[len(s)]
        
    def dfs(self, s, dict, stringlist):
        if self.check(s, dict):
            if len(s) == 0: Solution.res.append(stringlist[1:])
            for i in range(1, len(s)+1):
                if s[:i] in dict:
                    self.dfs(s[i:], dict, stringlist+' '+s[:i])
    
    def wordBreak(self, s, dict):
        Solution.res = []
        self.dfs(s, dict, '')
        return Solution.res

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM