[关闭]
@LIUHUAN 2020-02-02T10:22:04.000000Z 字数 2867 阅读 864

拆分单词从递归到迭代

algorithm


拆分单词

方法一:递归

  1. unordered_map<string, int> umap;
  2. bool wordbreak(string s, vector<string>& wordDict)
  3. {
  4. int n = s.size();
  5. for (auto& e : wordDict)
  6. umap[e] = 1;
  7. return wordBreak2(s, 0, n - 1);
  8. }
  9. bool wordBreak2(string s, int i, int j)
  10. {
  11. int n = s.size();
  12. if (i > j || j >= n) // base case #1
  13. return 0;
  14. string str = string(s.begin() + i, s.begin() + j + 1);
  15. if (umap.find(str) != umap.end()) { // base case #2
  16. return 1;
  17. }
  18. for (int k = i; k < j; ++k) {
  19. int x = wordBreak2(s, i, k);
  20. if (!x)// prune for false substr s[i,k]
  21. continue;
  22. int y = wordBreak2(s, k + 1, j);
  23. if (x && y)
  24. return 1;
  25. }
  26. return 0;
  27. }

方法二:转化为备忘录递归

  1. unordered_map<string, int> umap;
  2. unordered_map<string, int> rmap;
  3. bool wordbreak3(string s, vector<string>& wordDict)
  4. {
  5. int n = s.size();
  6. for (auto& e : wordDict)
  7. umap[e] = 1;
  8. return wordBreak2(s, 0, n - 1);
  9. }
  10. bool wordBreak3(string s, int i, int j)
  11. {
  12. int n = s.size();
  13. if (i > j || j >= n)
  14. return 0;
  15. string key = to_string(i) + "-" + to_string(j);
  16. if (rmap.find(key) != rmap.end()) {// has cached result s[i,j]
  17. return rmap[key];
  18. }
  19. string str = string(s.begin() + i, s.begin() + j + 1);
  20. if (umap.find(str) != umap.end()) { // base case for w in dictionary
  21. rmap[key] = 1;
  22. return 1;
  23. }
  24. for (int k = i; k < j; ++k) {
  25. int x = wordBreak2(s, i, k);
  26. if (!x)// prone the result s[i,k]
  27. continue;
  28. int y = wordBreak2(s, k + 1, j);
  29. if (x && y) {
  30. rmap[key] = 1; //cache result s[i,j]
  31. return 1;
  32. }
  33. }
  34. rmap[key] = 0;// cache result s[i,j]
  35. return 0;
  36. }

方法三:拆分单词(转化为迭代计算)

  1. bool wordBreak(string s, vector<string>& wordDict)
  2. {
  3. for (auto& e : wordDict)
  4. umap[e] = 1;
  5. int n = s.size();
  6. int f = 0;
  7. vector<vector<int>> dp(n, vector<int>(n, 0));
  8. for (int l = 0; l <= n; l++) {
  9. for (int i = 0; i < n - l; i++) {
  10. int j = i + l;
  11. if (j >= n)
  12. break;
  13. string str(s.begin() + i, s.begin() + j + 1);
  14. if (umap.find(str) != umap.end()) {
  15. dp[i][j] = 1;
  16. f = 1;
  17. }
  18. }
  19. }
  20. if (f == 0) {
  21. return 0;
  22. }
  23. if(dp[0][n-1])
  24. return 1;
  25. for (int l = 0; l < n; l++) {
  26. for (int i = 0; i < n - l; ++i) {
  27. int j = i + l;
  28. if (dp[i][j] == 1)
  29. continue;
  30. for (int k = i; k < j; ++k) {
  31. int c = dp[i][k] && dp[k + 1][j];
  32. dp[i][j] = max(c, dp[i][j]);
  33. if (dp[i][j])
  34. break;
  35. }
  36. }
  37. }
  38. return dp[0][n - 1];
  39. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注