LeetCode 140. 单词拆分 II

97 阅读1分钟

140. 单词拆分 II

难度困难669

给定一个字符串 s 和一个字符串字典 wordDict ,在字符串 s 中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。

注意: 词典中的同一个单词可能在分段中被重复使用多次。

 

示例 1:

输入: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
输出: ["cats and dog","cat sand dog"]

示例 2:

输入: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
输出: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
解释: 注意你可以重复使用字典中的单词。

示例 3:

输入: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
输出: []

 

提示:

  • 1 <= s.length <= 20
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 10
  • s 和 wordDict[i] 仅有小写英文字母组成
  • wordDict 中所有字符串都 不同

再刷算法题库的时候见到的这么一个题,思路是map检查合法性,DFS枚举答案,同时回溯处理。 记录答案的字符串,本来是写的 ans += str,但是这样回溯的时候不好处理(不好删掉这个字符串),索性直接在函数的变量里面加了一个ans + str + ' ',这样也不需要回溯处理。 可是本来以为这样处理会很慢, 没想到时间打败了100%的cpp代码,空间也还算可以。

image.png

class Solution {
private:
    vector<string> ret;
    map<string, bool> mp;
    int n;
public:
    void dfs(const string &s, int i,string ans) {
        if(i == n) {
            ans.pop_back();
            ret.push_back(ans);
            return ;
        }
        for(int j=i; j<n; j++) {
            string str = s.substr(i, j-i+1);
            if(mp[str] == true) {
                dfs(s, j+1, ans + str + ' ');
            }
        }
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        n = s.size();
        for(int i=0; i<wordDict.size(); i++) {
            mp[wordDict[i]] = true;
        }
        
        dfs(s,0, "");
        return ret;
    }
};