140. 单词拆分 II(回溯)

 

思路
难度困难

给定一个字符串 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"]
输出:[]

 

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        res = []
        
        def backtrack(path, start):
            if start == len(s):
                res.append(" ".join(path))
                return       
            for word in wordDict:
                if s.startswith(word, start):
                    backtrack(path + [word], start + len(word))
        
        backtrack([], 0)
        return res

 

 

 

class Solution {

public:
    vector<string> res;

    void backtrack(string& path, string& path_str,string s,vector<string>& wordDict) {
        if (path_str.size() > s.size()) {
            return;
        }
        if (path_str == s) {
            path.pop_back();//pop 最后一个空格
            res.emplace_back(path);
        }
        for(auto word : wordDict) {
            int sz = path_str.size();
            int sz2 = path.size();
            path+=word;
            path+=" ";
            path_str+=word;
            backtrack(path,path_str,s,wordDict);
            path_str = path_str.substr(0,sz);
            path = path.substr(0,sz2);
        }


    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {

        vector<string> path;
        string a = "";
        string a2= "";
        backtrack(a2,a,s,wordDict);
        return res;
    }
};

 

posted @ 2022-06-11 15:41  乐乐章  阅读(39)  评论(0编辑  收藏  举报