Word Break II

来源:互联网 发布:linux中开启ftp端口号 编辑:程序博客网 时间:2024/06/06 09:20

题目描述:

Given a string s and a dictionary of words dict, add spaces ins 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"].

dfs会超时:

public class Solution {    public List<String> wordBreak(String s, Set<String> wordDict) {List<String> result=new ArrayList<String>();StringBuilder sb=new StringBuilder();getScentence(s, wordDict, 0, sb, result);return result;    }public void getScentence(String s, Set<String> wordDict,int start,StringBuilder sb,List<String> result){if(start==s.length()){int len=sb.length();String str=sb.delete(len-1, len).toString();result.add(str);return;}int len=sb.length();for(int i=start+1;i<=s.length();i++){String substr=s.substring(start, i);if(wordDict.contains(substr)){sb.append(substr).append(" ");getScentence(s, wordDict, i, sb, result);sb.delete(len, len+substr.length()+1);//这里要+1,小心细节- -!}}}} 
带备忘录的dfs算法:
public class Solution {    Map<String, List<String>> mem = new HashMap<>();public List<String> wordBreak(String s, Set<String> wordDict) {    if (mem.get(s) != null) return mem.get(s);    List<String> result = new ArrayList<>();    if (wordDict.contains(s)) result.add(s);    for (int i = 1; i < s.length(); i++) {        String word = s.substring(0, i);        if (wordDict.contains(word)) {            List<String> tmp = wordBreak(s.substring(i), wordDict);            for (String str : tmp) {                result.add(word + " " + str);            }        }    }    mem.put(s, result);    return result;}}





0 0