Word Break II

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

dfs超时

public class Solution {
    public List wordBreak(String s, Set dict) {
       LinkedList res=new LinkedList();
       LinkedList path=new LinkedList();
       if(s==null || dict==null || dict.size()==0) return res;
       
       int n=s.length();
       boolean []f=new boolean[n+1];
       boolean [][]prev=new boolean[n+1][n];
       f[0]=true;
       //dp
       for(int i=1;i<=n;i++){
           for(int j=i-1;j>=0;j--){
               if( f[j] && dict.contains( s.substring(j,i) ) ){
                   f[i]=true;
                   prev[i][j]=true;
               }
           }
       }

       getPath(s.length(),s,prev,res,path);
       return res;
    }
    //dfs
    public void getPath(int curr,String s, boolean [][]prev,LinkedList res,LinkedList path){
        if(curr==0){
            StringBuilder sb=new StringBuilder();
            for(String ss : path){
                sb.append(ss);
                sb.append(" ");
            }
            res.add(sb.toString().trim());
        }
        for(int i=0;i




你可能感兴趣的:(LeetCode)