Monday, August 11, 2014

Word Break II @leetcode

[LeetCode] WordBreak II, Solution

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

This is a very typical problem of combination of back tracking and DP.

Basic idea is, we start from first letter in string S, then we check every substr we have so far to see if it's in dict.
If it's in dict, then we go iteratively to search the rest substr to find out all combinations. However, it will lead to redundant
searching during the iteration. Thus we can use an array to record the search result to avoid repeated searching.

We define res[i+1] = true, means substr(i,n) has combination in dict, otherwise it doesn't.

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...