Word Break II[动态规划&DFS]

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

请参考LeetCode-Word Break查看该题的第一个版本:判断是否可分词成功。但是这一题,不仅要判断是否可以分词,还要找到所有的分词结果。

第一题是用dp[i]表示 字符串s[0....i-1]是否可以分词成功。

为了记录是怎么分词的,我们可以用dp[i]表示 字符串s[0.....i-1]的最后一个分词word,则s[0.....i-1]的倒数第二个分词即为dp[o....i-word.length()-1]。但这种方法只能记录一种分词方法,因此有必要把 dp[i] 定义 List<String>,这样就可以表示多种分词方法,最后使用DFS搜索,找到所有的分词方法。

例如对于上面的例子:  s.length()=10, 则 dp[10] = {“cat”}, dp[7]={“and”,”sand”}, dp[4]={“cats”}, dp[3]={“cat”}, dp[0]={}, 其它的都为null。

dfs搜索的时,可以从后向前,也可以从前向后,只要保证最终结果的顺序即可。下面是用的从后向前搜索。

public class Solution {
  public static List<String> wordBreak(String s, Set<String> dict) {
    List<String> dp[] = new ArrayList[s.length()+1];
    dp[0] = new ArrayList<String>();
    for(int i=0; i<s.length(); i++){
      //i是开始位置
      if( dp[i] == null ) continue; //前面的部分必须是可以匹配的
      for(String word:dict){
        int len = word.length();
        int end = i+len;
        if(end > s.length()) continue;
        if(s.substring(i,end).equals(word)){
          if(dp[end] == null){
            dp[end] = new ArrayList<String>();
          }
          dp[end].add(word);//记录上一个位置
        }
      }
    }

    List<String> ans = new LinkedList<String>();
    if(dp[s.length()] == null) return ans; 
    ArrayList<String> tmp = new ArrayList<String>();
    dfsStringList(dp,s.length(),ans, tmp);
    return ans;
  }

  public static void dfsStringList(List<String> dp[],int end,List<String> res, ArrayList<String> tmp){
    if(end <= 0){
      String ans = tmp.get(tmp.size()-1);
      for(int i=tmp.size()-2; i>=0; i--)
        ans += (" " + tmp.get(i) );
      res.add(ans);
      return;
    }
    for(String str:dp[end]){
      tmp.add(str);
      dfsStringList(dp,end-str.length(), res, tmp);
      tmp.remove(tmp.size()-1);
    }
  }
}

当然也有其他的解法,这个只是参考,效率其实还可以。

转自:http://www.tuicool.com/articles/ZVJJRrF

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值