【LeetCode】140. Word Break II

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:
[]

链接:https://leetcode.com/problems/word-break-ii/description/

题解:动态规划,主要用dp数组记录递归状态,转移方程:定义状态s中前i个字符串所对应的可能句子dp[i]={dp[j-1]+str[j:i]}其中str[j:i]为字典中单词,把所有满足结果都遍历一遍就是答案,注意这里要用map记录每个i所对应的结果即记忆化搜索,也可以定义为从末尾到第i个,这里第一次提交错误是分界处j-1没有用-1还有需要考虑边界情况即整个都是str单词直接加入res中

class Solution {
public:
    

    vector<string> wordBreak(string s, vector<string>& wordDict) {
        map<int,vector<string>> mp;
        unordered_set<string> dict;
        for(auto str:wordDict){
            dict.insert(str);
        }
        vector<string> ans=dfs(s,dict,mp,0);
        return ans;
    }
    vector<string> dfs(string s,unordered_set<string> dict, map<int,vector<string>>& mp,int index){
        if(mp.find(index)!=mp.end()) return mp[index];
        vector<string> res;
        for(int i=index+1;i<=s.size();i++){
            string str=s.substr(index,i-index);
            if(dict.find(str)!=dict.end()){
                if(i==s.size()) res.push_back(str);
                vector<string> tmp=dfs(s,dict,mp,i);
                for(auto ss:tmp){
                    res.push_back(str+' '+ss);
                }
            }
        }
        mp[index]=res;
        return res;
    }
};

还可以进一步优化设置一个flag数组来标记改处无法继续分割完成剪枝

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值