算法学习之回溯法(leetcode 140. Word Break II)

leetcode 140. 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来思路来思考
需要设计好一个好的核心函数至关重要。
最直接的思路应该是
返回值为最后的结果集合,两个参数为字符串s,字典wordDict,如下

List<String> myDFS(String s, Set<String> wordDict)

然而,经过测试发现超时,所以添加一个HashMap保留中间结果。
源代码如下

public class Solution {
    //此函数的含义解释
    //输入给定字符串s, 给定词典wordDict, 保存结果的HashMap
    //返回值为s的所有分隔结果,为<分隔结果1,分隔结果2,...>
    public List<String> myDFS(String s, Set<String> wordDict, HashMap<String, LinkedList<String>> result){
        //如果已经计算过了,则直接返回结果,不用重新计算了
        if(result.containsKey(s)){
            return result.get(s);
        }

        //否则没有计算过,继续
        //声明一个保存结果的变量
        LinkedList<String> cur = new LinkedList<String>();
        //如果此时s的长度为0
        if(s.isEmpty()){
            //这个地方为什么不直接返回cur呢,待会看下
            //这边如果不添加"",这个责结果为空,所以前面匹配成功的就无法添加到结果中去了。
            cur.add("");
            return cur;
        }
        for(String word : wordDict){
            //如果s是以word作为prefix的话,可以尝试一下
            if(s.startsWith(word)){
                List<String> temp = myDFS(s.substring(word.length()), wordDict, result);
                for(String subTemp : temp){
                    cur.add(word + (subTemp.isEmpty() ? "" : " " + subTemp));
                }
            }
        }
        result.put(s, cur);
        return cur;
    }
    public List<String> wordBreak(String s, Set<String> wordDict) {
        //用来保存<字符串,字符串所有的分割结果>
        HashMap<String, LinkedList<String>> result = new HashMap<String, LinkedList<String>>();

        return myDFS(s, wordDict, result);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值