Word Break II - LeetCode

Word Break II - LeetCode

题目:
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”
]


最近想复习一下C++和一些算法,很久没写C++代码基本全忘了,于是LeetCode上找了一道比较简单的题目练一下。
一开始都忘了递归这个东西,后来才想起来,这道题用递归做很方便。
catsanddog分成catsanddog后,后面的sanddog这部分就成了新的s,可以用相同的方法解决。算出sanddog所有拆分方法vector subResult之后,再把cat加到subResult中的每一个字符串前面就行。

刚开始写的代码

class Solution {
     
public:
    vector<string> wordBreak(string s, vector<string> & wordDict) {
     
      vector<string> a;
      for (int i = 0; i < wordDict.size(); i++) {
     
        string temp = wordDict[i];
        int t = s.find(temp);
        if (t == 0) {
     

          if (temp.length() == s.length()) {
     
            a.push_back(temp);
          } else {
     
            vector<string> subResult = wordBreak(s.substr(temp.length()), wordDict);
            for (int i = 0; i < subResult.size(); i++) {
     
              a.push_back(temp + " " + subResult[i]);
            }
          }
        } else {
     
          continue;
        }
      }
      return a;
    }
};

答案应该是对的,不过会超时,看了答案才想起了动态规划这个方法。

class Solution {
     
public:
    vector<string> wordBreak(string s, vector<string> & wordDict) {
     
      if (dp.count(s)) return dp[s];
      vector<string> a;
      for (int i = 0; i < wordDict.size(); i++) {
     
        string temp = wordDict[i];
        // int t = s.find(temp);
        if (s.substr(0, temp.length()) == temp) {
     

          if (temp.length() == s.length()) {
     
            a.push_back(temp);
          } else {
     
            vector<string> subResult = wordBreak(s.substr(temp.length()), wordDict);
            for (int i = 0; i < subResult.size(); i++) {
     
              a.push_back(temp + " " + subResult[i]);
            }
          }
        } else {
     
          continue;
        }
      }
      dp[s] = a;
      return a;
    }
    unordered_map<string, vector<string> > dp;
};

如果不用动态规划,那么某一个子字符串的拆分方法可能会计算好几次。

你可能感兴趣的:(算法分析与设计,leetCode,动态规划)