在这里插入图片描述

c++ 递归超时

class Solution {

public:
    bool dp(string s, string p,int i,int j ){
        if(i==0 && j==0)
            return true;
        if(j==0) return false;
        bool  firstmatch=i>0&&(p[j-1]==s[i-1]||p[j-1]=='?');
        if(p[j-1]=='*')
             return dp(s,p,i,j-1)||(i>0&& dp(s,p,i-1,j));
        else{
         
            return firstmatch && dp(s,p,i-1,j-1);
        } 
      
    }
    bool isMatch(string s, string p) {
       
        return dp(s,p,s.size(),p.size());
       }
};

记忆化

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        memo = {}
        def dp(i, j):
            if(i==0 and j==0):
                return True;
            if(j==0):
                return False;
            if(i,j)in memo:
                return memo[i,j]
            # ans=False 
            # i==0,j>0即s为空串时,p[j]!=*时,返回False.对于P[j]==*,时由一下分支处理
            firstmatch=i>0 and(p[j-1]==s[i-1]or p[j-1]=='?')
            if p[j-1]=='*':
                ans= dp(i,j-1)or (i>0 and dp(i-1,j))
            else:
                ans= firstmatch and dp(i-1,j-1)
            memo[i,j]=ans
            return ans

        return dp(len(s), len(p))    

动态规划

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        dp = [[False] * (len(p) + 1) for _ in range(len(s) + 1)]
        dp[0][0]=True
        for i in range(0,len(s)+1):
            for j in range(1,len(p)+1):
                firstmatch=i>0 and (p[j-1]==s[i-1]or p[j-1]=='?')
                if p[j-1]=='*':
                    dp[i][j]=dp[i][j-1]or (i>0 and dp[i-1][j])
                else:
                    dp[i][j]= firstmatch and dp[i-1][j-1]
        return dp[len(s)][len(p)]  

更多推荐