leetcode 140.单词拆分II

leetcode 140.单词拆分II

题干

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。

示例:
输入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
输出:
[
  “cats and dog”,
  “cat sand dog”
]

题解

由题意很容易想到回溯算法,但显然如下的写法对于有大量重复数据的样例来说会超时(譬如全是a的字符串,字典是"a",“aa”,“aaa”…)

class Solution {
public: 
    vector<string> ans;
    unordered_set<string> words;
    void dfs(string word,string tempAns,string s,int index){
        if(index == s.length() ){
            ans.push_back(tempAns);
            return;
        }
        while(index < s.length() ){
            word = word + s[index];
            if(words.count(word) != 0){
                if(tempAns.empty() ){
                    dfs({},tempAns+word,s,index+1);
                }
                else{
                    dfs({},tempAns+' '+word,s,index+1);
                }
            }
            index++;
        }
        return;
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        int n = s.length();
        for(int i=0;i<wordDict.size();i++){
            words.insert(wordDict[i]);
        }
        dfs({},{},s,0);
        return ans;
    }
};

记忆化搜索
* 注意点在于递归函数的开头判断ans.count(index)的部分

class Solution {
public:
    unordered_map<int,vector<string> > ans;
    unordered_set<string> words;

    void dfs(string word,string tempAns,string s,int index){
        if(ans.count(index) == 0){																//当以index为起始下标的ans为空时才进行操作,如果不进行此步会出现重复答案(仍然超时)
            if(index == s.length() ){															//当index为s.length()时,将ans[index]置空,意为以index为起始下标能构成的句子为空
                ans[index] = {""};
                return;
            }
            while(index < s.length() ){
                word = word + s[index];
                if(words.count(word) != 0){														//当s中可以构造出词典中存在的单词时
                    dfs({},tempAns+word,s,index+1);
                    for(auto sentence:ans[index+1]){											//遍历ans[index+1]中的所有句子,即以index+1为起始下标的所有可能构成的句子
                        if(sentence.empty())
                            ans[index-word.length()+1].push_back(word);
                        else
                            ans[index-word.length()+1].push_back(word + " " + sentence);		//将当前能够组成的单词拼接到ans[index+1]中句子的前端,并将构成的新句子推入以index-word.length()+1为下标的ans
                    }
                }
                index++;
            }
        }
        return;
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        int n = s.length();
        for(int i=0;i<wordDict.size();i++){
            words.insert(wordDict[i]);
        }
        dfs({},{},s,0);
        return ans[0];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值