LeetCode刷题笔录Word Break II

来源:互联网 发布:mac怎么切换独立显卡 编辑:程序博客网 时间:2024/05/17 10:55

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;            }        }    }}


0 0