标签:color als com 不容易 div == const matching 搜索
problem:https://leetcode.com/problems/wildcard-matching/
用记忆化搜索做的,不容易出错:
class Solution { public: vector<vector<int>> dp; bool isMatch(const string& s, const string& p, int i, int j) { if(i >= s.size() && j >= p.size()) return true; if(j >= p.size()) return false; if(dp[i][j] != 2) return dp[i][j]; if(i < s.size() && (s[i] == p[j] || p[j] == ‘?‘)) { return dp[i][j] = isMatch(s, p, i + 1, j + 1); } if(p[j] == ‘*‘) { for(int k = i; k <= s.size(); k++) { if(isMatch(s, p, k, j + 1)) return dp[i][j] = true; } } return dp[i][j] = false; } bool isMatch(string s, string p) { dp.resize(s.size() + 1, vector<int>(p.size() + 1, 2)); return isMatch(s, p, 0, 0); } };
非递归:
class Solution { public: vector<vector<bool>> dp; bool isMatch(string s, string p) { dp.resize(s.size() + 1, vector<bool>(p.size() + 1)); dp[0][0] = true; for(int i = 1;i <= s.size();i++) { dp[i][0] = false; } for(int j = 0;j < p.size(); j++) { if(p[j] == ‘*‘) dp[0][j + 1] = true; else break; } for(int i = 0;i < s.size();i++) { for(int j = 0;j < p.size();j++) { if(p[j] == ‘*‘) { dp[i + 1][j + 1] = dp[i + 1][j] || dp[i][j + 1]; } else { dp[i + 1][j + 1] = (s[i] == p[j] || p[j] == ‘?‘) && dp[i][j]; } } } return dp[s.size()][p.size()]; } };
[动态规划] leetcode 44 Wildcard Matching
标签:color als com 不容易 div == const matching 搜索
原文地址:https://www.cnblogs.com/fish1996/p/11329889.html