码迷,mamicode.com
首页 > 其他好文 > 详细

Word Break II 解答

时间:2015-11-02 06:40:56      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

Question

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"].

Solution

这题的基本思路是用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

 

Word Break II 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4929133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!