單詞拆分II

#單詞拆分II
#給一字串s和單詞的字典dict,在字串中增長空格來構建一個句子,而且全部單詞都來自字典。
#返回全部有可能的句子。
#EXAMPLE:
#給一字串lintcode,字典爲["de", "ding", "co", "code", "lint"]
#結果爲["lint code", "lint co de"]。

class Solution:
    """
    @param: s: A string
    @param: wordDict: A set of words.
    @return: All possible sentences.
    """
    def wordBreak(self, s, wordDict):
        # write your code here
        return self.helper(s, wordDict, {})

    def helper(self, s, wordDict, memory):
        if s in memory: #string若是有記錄,直接調用返回以節省時間
            return memory[s]
        res = []
        for i in range(len(s)-1):
            cut = s[:i+1]
            if cut in wordDict:
                sub = self.helper(s[i+1:], wordDict, memory)
                for j in sub:
                    res.append(cut + ' ' + j)
        if s in wordDict:
            res.append(s)
        memory[s] = res #記住這個string有多少種拆分方法
        return resapp

相關文章
相關標籤/搜索