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

    Approach #1: Recursive. [C++]

    class Solution {
    private:
        unordered_map<string, vector<string>> m;
        vector<string> combine(string word, vector<string> prev) {
            for (int i = 0; i < prev.size(); ++i) {
                prev[i] += ' ' + word;
            }
            return prev;
        }
        
    public:
        vector<string> wordBreak(string s, vector<string>& wordDict) {
            unordered_set<string> wordDict_(wordDict.begin(), wordDict.end());
            if (m.count(s)) return m[s];
            vector<string> result;
            if (wordDict_.find(s) != wordDict_.end()) {
                result.push_back(s);
            }
            for (int i = 1; i < s.size(); ++i) {
                string word = s.substr(i);
                if (wordDict_.find(word) != wordDict_.end()) {
                    string rem = s.substr(0, i);
                    vector<string> prev = combine(word, wordBreak(rem, wordDict));
                    result.insert(result.end(), prev.begin(), prev.end());
                }
            }
            m[s] = result;
            return result;
        }
    };
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    mdx 根据维度Hierarchy节点的名字来filter节点,搜索节点
    学习C++.Primer.Plus 8 函数探幽
    学习C++.Primer.Plus 7 函数
    学习C++.Primer.Plus 6 分支语句和逻辑操作符
    学习C++.Primer.Plus 5 循环和关系表达式
    学习C++.Primer.Plus 4 复合类型
    NYoj_171聪明的kk
    NYoj_104最大和
    希尔排序
    NYoj_49开心的小明
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10352415.html
Copyright © 2020-2023  润新知