140-分隔单词II

Description

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. You may assume the dictionary does not contain duplicate words.
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”].


问题描述

给定非空字符串s和非空字符串列表wordDict,向s中加入空格使得空格分隔的每个单词出现在wordDict中。wordDict不包含重复单词。返回s加入空格后所有可能的字符串。


问题分析

dfs + memorization

算法思想以s = “catsanddog”,dict = [“cat”, “cats”, “and”, “sand”, “dog”]为例

s.substring(0, 3) = “cat”出现在dict中,那么递归s.substring(3),将”cat”添加到返回结果中
得到的结果是”cat sand dog”
s.substring(0, 4) = “cats”出现在dict中,那么递归s.substring(4),将”cats”添加到返回结果中
得到的结果是”cats and dog”
综合一下
得到[“cat sand dog”, “cats and dog”]


解法(dfs + memorization)

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        //字典集合
        Set<String> dict = new HashSet();

        for(String str : wordDict)  dict.add(str);

        return backTrack(s, dict, new HashMap());       
    }
    public List<String> backTrack(String s, Set<String>dict, Map<String, List<String>> memo){
        //memo保存字符串s对应的所有分隔可能性
        if(memo.containsKey(s)) return memo.get(s);


        List<String> res = new ArrayList();
        for(int i = 0;i < s.length();i++){
            String temp = s.substring(0, i + 1);
            //若字典集合包含temp,递归字串s.substring(i + 1),将temp添加到返回结果中
            //注意,若到达末尾,直接加入temp即可
            if(dict.contains(temp)){
                if(i == s.length() - 1){
                    res.add(temp);
                }else{
                    List<String> subres = backTrack(s.substring(i + 1), dict, memo);
                    if(subres.size() != 0){
                        for(String str : subres){
                            res.add(temp + " " + str);                    
                        }   
                    }
                }
            }
        }
        memo.put(s, res);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值