LeetCode Top Interview Questions 140. Word Break II (Java版; Hard)

welcome to my blog

LeetCode Top Interview Questions 140. Word Break II (Java版; Hard)

题目描述
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
 "cats and dog",
 "cat sand dog"
]
Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
 "pine apple pen apple",
 "pineapple pen apple",
 "pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:

Input:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
Output:
[]
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int n = s.length();
        if(n==0 || wordDict.size()==0){
            return list;
        }
        HashMap<String, List<String>> map = new HashMap<>();
        list = dfs(wordDict, s, map);
        return list;
    }

    private List<String> dfs(List<String> wordDict, String s, HashMap<String, List<String>> map){
        //递归出口
        if(map.containsKey(s)){
            return map.get(s);
        }
        List<String> res = new ArrayList<>();
        int n = s.length();
        //递归出口
        if(n==0){
            res.add("");
            return res;
        }
        for(String word : wordDict){
            if(s.startsWith(word)){
                List<String> tmp = dfs(wordDict, s.substring(word.length()), map);
                if(tmp.size()!=0){
                    for(String t : tmp){
                        if(t.equals("")){
                            res.add(word);
                        }else{
                            res.add(word+" "+t);
                        }
                    }
                }
            }
        }
        map.put(s, res);
        return res;
    }
}
//超时  31/36
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int n = s.length();
        if(n==0 || wordDict.size()==0){
            return list;
        }
        backtrace(list, wordDict,s, sb, 0);
        return list;
    }

    private void backtrace(List<String> list, List<String> wordDict, String s, StringBuilder sb, int i){
        int n = s.length();
        if(i==n){
            list.add(sb.toString().trim());
            return;
        }
        for(int j=i; j<n; j++){
            String str = s.substring(i, j+1);
            if(wordDict.contains(str)){
                int start = sb.length();
                sb.append(str).append(" ");
                backtrace(list, wordDict, s, sb, j+1);
                sb.delete(start, sb.length());
            }
        }
    }
}
第一次做; DFS, 回溯, 哈希表形式的memo; 递归函数的返回值; 核心: s.startsWith(); base case时向res中加入空串
/*
暴力递归; DFS; 回溯; 使用memo数组优化
回溯法都能使用memo进行优化吗? 感觉可以, 因为回溯法有个最大的特点: 与前面无关, 也就是说, 处理到索引i, 最终的结果只跟[i+1,end]有关, 跟[0,i-1]无关; 
像0-1背包问题就没法使用memo数组优化,因为最终结果跟[0,end]都有关
不过这道题的memo结构比较复杂,是个哈希表, 第一次见
*/
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        return dfs(wordDict, s, new HashMap<String,List<String>>());
    }
    public List<String> dfs(List<String> wordDict, String s, HashMap<String, List<String>> memo){
        if(memo.containsKey(s))
            return memo.get(s);
        //当前字符串对应的结果
        List<String> res = new ArrayList<>();
        //base case
        if(s.isEmpty()){
            //核心: s为空串时,必须在res中添加个空串, 为了能进入下面的内循环, 加入空串后才能进入内循环, 否则整个流程的结果将是空
            res.add("");
            return res;
        }
        //
        for(String word : wordDict){
            //核心: 使用startswith()找出字符串最前面部分对应的单词
            if(s.startsWith(word)){
                List<String> tmp = dfs(wordDict, s.substring(word.length()), memo);
                //base case保证了tmp不是null, 所以下面的遍历不会报空指针异常错误:java.lang.NullPointerException
                for(String cur : tmp){
                    //核心:和base case配合                    
                    res.add(word+(cur.isEmpty()?"":" ")+cur);
                }
            }
        }
        //记录下来, 减少重复问题的计算
        memo.put(s, res);
        //返回当前字符串对应的所有结果
        return res;
    }
}
第一次做; 暴力递归; DFS; 回溯; 核心:恢复现场时, 要使用指定索引的方式删除元素; 超时31/39
/*
暴力递归; 回溯; 看看s[index,end]是不是有效单词, 是的话执行新条件新递归; 不是的话继续下一轮循环

回溯就是DFS的体现

报错:出现了重复
输入
"aaaaaaa"
["aaaa","aa","a"]
输出
["a a a a a a a","a a a a a aa","a a a a aa a","a a a aa a a",
"a aa a a aa","a a a aaaa","a a aa a a a","aa a a a aa","a a aa aa a",
"a a aaaa a","a aa a a a a","aa a a a aa","a a aa aa a","aa a aa a a",
"aa aa a aa","a aa aaaa","a aaaa a a","aaaa a aa","aa a a a a a",
"aa a a a aa","a a aa aa a","aa a aa a a","aa aa a aa","a aa aaaa",
"aa aa a a a","aa aa a aa","aa aa aa a","aa aaaa a","aaaa a a a",
"aaaa a aa","aaaa aa a"]
*/
class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        List<String> res = new ArrayList<>();
        List<String> al = new ArrayList<>();
        backtrace(res, al, wordDict, s, 0);
        return res;
    }
    public void backtrace(List<String> res, List<String> al, List<String> wordDict, String s, int index){
        //base case
        if(index==s.length()){
            StringBuilder sb = new StringBuilder();
            for(String ss : al)
                sb.append(ss).append(" ");
            res.add(sb.toString().trim());
            return;
        }
        //从index位置开始处理s
        for(int i=index; i<s.length(); i++){
            //取出s[index,i], 要时刻明确递归函数处理的是哪部分
            String cur = s.substring(index, i+1);
            if(wordDict.contains(cur)){
                //改变现场
                al.add(cur);
                //新条件新递归; 从i+1位置开始处理
                backtrace(res, al, wordDict, s, i+1);
                //恢复现场; 核心:要删除最后一个, 也就是说得用索引指定待删除元素的位置
                // al.remove(cur);
                al.remove(al.size()-1);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值