140. 单词拆分 II(回溯)
给定一个字符串 s
和一个字符串字典 wordDict
,在字符串 s
中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。
注意:词典中的同一个单词可能在分段中被重复使用多次。
示例 1:
catsanddog
["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; } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2018-06-11 172. Factorial Trailing Zeroes(阶乘中0的个数 数学题)
2018-06-11 171. Excel Sheet Column Number(简单数学题)
2018-06-11 200. Number of Islands(DFS)