LeetCode刷题笔录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"].

这题要求出所有的结果,显然是要递归了。先写个brute force的解法。

public class Solution {
    public List<String> wordBreak(String s, Set<String> dict) {
        List<String> res = new ArrayList<String>();
        if(s.length() == 0 || s == null)
            return res;
        recursive(s, 0, dict, "", res);
        return res;
    }
    
    public void recursive(String s, int index, Set<String> dict, String string, List<String> res){
        if(index >= s.length()){
            res.add(string);
            return;
        }
        StringBuilder builder = new StringBuilder();
        for(int i = index; i < s.length(); i++){
            builder.append(s.charAt(i));
            if(dict.contains(builder.toString())){
                String str = string.isEmpty() ? builder.toString() : (string + " " + builder.toString());
                recursive(s, i + 1, dict, str, res);
            }
        }
    }
}


大数据集是通不过的。网上看到了一个剪枝的办法,就是利用DP的思想,如果某个点i在之前的搜索中没有得到结果,那么以后就不进行搜索了。

public class Solution {
    public List<String> wordBreak(String s, Set<String> dict) {
        List<String> res = new ArrayList<String>();
        if(s.length() == 0 || s == null)
            return res;
        boolean[] possible = new boolean[s.length() + 1];
        Arrays.fill(possible, true);
        recursive(s, 0, dict, "", res, possible);
        return res;
    }
    
    public void recursive(String s, int index, Set<String> dict, String string, List<String> res, boolean[] possible){
        if(index >= s.length()){
            res.add(string);
            return;
        }
        StringBuilder builder = new StringBuilder();
        for(int i = index; i < s.length(); i++){
            builder.append(s.charAt(i));
            //only perform search if there are possible solutions in level i + 1
            if(dict.contains(builder.toString()) && possible[i + 1]){
                String str = string.isEmpty() ? builder.toString() : (string + " " + builder.toString());
                int beforeSearch = res.size();
                recursive(s, i + 1, dict, str, res, possible);
                //if the result size is not changed after the search, then there is no solution at i
                if(beforeSearch == res.size())
                    possible[i + 1] = false;
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值