标签:
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"]
.
这题的基本思路是用recursion,每次都只研究第一刀切在哪儿,然后对剩下的substring做递归。但是我们发现其实可以借助DP的思想,存下来部分中间结果值。这种思想也叫 Memorized Recursion。
Memorized recursion并不是一个很好的方法,但是当遇到time limit exceed时可以想到它来拿空间换时间
1 class Solution: 2 # @param s, a string 3 # @param dict, a set of string 4 # @return a list of strings 5 def wordBreak(self, s, dict): 6 self.dict = dict 7 # cache stores tmp results: key: substring value: list of results 8 self.cache = {} 9 return self.break_helper(s) 10 11 def break_helper(self, s): 12 combs = [] 13 if s in self.cache: 14 return self.cache[s] 15 if len(s) == 0: 16 return [] 17 18 for i in range(len(s)): 19 if s[:i+1] in self.dict: 20 if i == len(s) - 1: 21 combs.append(s[:i+1]) 22 else: 23 sub_combs = self.break_helper(s[i+1:]) 24 for sub_comb in sub_combs: 25 combs.append(s[:i+1] + ‘ ‘ + sub_comb) 26 27 self.cache[s] = combs 28 return combs
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4929133.html