Leetcode 140 Word Break II

题意:给定一个string以及一个wordDict,要求返回一个vector<string> ,这个vector中的string都是word Dict中的组合

Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]

Output: ["cats and dog","cat sand dog"]

想法:backtracking, 想象一下每一轮你要干什么,首先拿wordDict中的每个单词去填写,如果对不上号,你就填下一个单词直到最后填到单词末尾就结束了。

cpp 复制代码
class Solution {
public:
    vector<string> ret;
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        dfs(s, "", 0 , wordDict);
        return ret;
    }

    void dfs(string& s, string cur, int st, vector<string>& wordDict) {
        if (st == s.size()) {
            cur.pop_back();
            ret.push_back(cur);
        }
        
        for(auto word : wordDict) {
            if(st + word.size() <= s.size()) {
                if(word == s.substr(st, word.size())) {
                    string temp = cur;
                    cur += word;
                    cur += " ";
                    dfs(s, cur, st+word.size(), wordDict);
                    cur = temp;
                }
            }
        }
    }
};

时间复杂度是指数级别的,递归栈空间是O(n)

相关推荐
SizeTheMoment17 天前
List介绍
1024程序员节
开利网络19 天前
产业互联网+三融战略:重构企业增长密码
大数据·运维·服务器·人工智能·重构·1024程序员节
wei_shuo1 个月前
从数据中台到数据飞轮:实现数据驱动的升级之路
1024程序员节·数据飞轮
玖剹1 个月前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节
jamison_12 个月前
文心一言与 DeepSeek 的竞争分析:技术先发优势为何未能转化为市场主导地位?
人工智能·ai·chatgpt·gpt-3·1024程序员节
NaZiMeKiY2 个月前
HTML5前端第六章节
前端·html·html5·1024程序员节
jamison_12 个月前
颠覆未来:解锁ChatGPT衍生应用的无限可能(具体应用、功能、付费模式与使用情况)
ai·chatgpt·1024程序员节
NaZiMeKiY3 个月前
HTML5前端第七章节
1024程序员节
earthzhang20213 个月前
《Python深度学习》第四讲:计算机视觉中的深度学习
人工智能·python·深度学习·算法·计算机视觉·numpy·1024程序员节
明明真系叻3 个月前
2025.3.2机器学习笔记:PINN文献阅读
人工智能·笔记·深度学习·机器学习·1024程序员节·pinn