Leetcode140: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 + dynamic programming,word break I里面是用boolean数组来存储字符串在某一个位置是否能被分割。 那么word break II就是用一个ArrayList的dp[] 数组来存储 String在某一个位置可以往前数,可以构成多少个在Dict里面的单词

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
       ArrayList<String> dp[] = new ArrayList[s.length()+1];
        dp[0]  = new ArrayList<String>();
        for(int i=0;i<s.length()+1;i++){
        if( dp[i] == null ) 
            continue; 
            for(String a:wordDict){
                int end = a.length()+i;
                if(end>s.length()) continue;
                if(s.substring(i,end).equals(a)){
                    if(dp[end]==null) {dp[end] = new ArrayList<String>();}
                    dp[end].add(a);
                }
            }
        }
        List<String> result = new ArrayList<String>();
        if(dp[s.length()]==null) return result;
        ArrayList<String> temp = new ArrayList<String>();
        dfs(dp,result,s.length(),temp);
        return result;
    }
    public void dfs(ArrayList<String>[] dp,List<String> result,int end,ArrayList<String> temp){
        if(end<=0){
            String path = temp.get(temp.size()-1);
            for(int i=temp.size()-2; i>=0; i--){
                path += " " + temp.get(i) ;
            }
            result.add(path);
            return;
        }
        for(String a:dp[end]){
            // System.out.println(dp[end]);
            temp.add(a);
            System.out.println(temp);
            dfs(dp,result,end-a.length(),temp);
            temp.remove(temp.size()-1);
        }
    }
}

原来没有仔细的想过dfs里面执行代码的过程,比如test case是
***s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].*

Your stdout:
[dog]
[dog, sand]
[dog, sand, cat]
[dog, and]
[dog, and, cats]
当temp = [dog, sand, cat],代码执行到 temp.remove(temp.size()-1)的时候,应该怎么执行,这个时候应该是进入for循环里面,看看for循环还能不能继续往下面执行了,如果不能继续往下执行的话,这个dfs函数就执行完毕,执行父辈的dfs函数,继续remove单词 sand 这个和subset里面的dfs执行是一样一样的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值