从递归到memo到动态规划

//memo,记忆化搜索

class Solution {
    int[][] memo;
    public boolean wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        memo=new int[n+1][n+1];
        for(int i=0;i<=n;i++)
            for(int j=0;j<=n;j++)
                memo[i][j]=-1;
        return breakWord(s,wordDict,0,n);
    }
    public boolean breakWord(String s,List<String> wordDict,int l,int r)
    {
         if(r==0)
             return true;
         if(memo[l][r]!=-1)
                return memo[l][r]==1;  
        memo[l][r]=0;
        for(int i=r-1;i>=0;i--)
        {
           if(helper(s.substring(i,r),wordDict)&&breakWord(s,wordDict,l,i))
           {
               memo[l][r]=1;
               break;
           }
        }
        return memo[l][r]==1;
    }
    public boolean helper(String s,List<String> wordDict)
    {
        for(String str:wordDict)
        {
            if(str.equals(s))
                return true;
        }
        return false;
    }
}

//动态规划

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int n=s.length();
        boolean[] dp=new boolean[n+1];
        dp[0]=false;
        for(int i=1;i<=n;i++)
        {
            if(helper(s.substring(0,i),wordDict))
                dp[i]=true;
            else
            {
                dp[i]=false;
                for(int j=i-1;j>=0;j--)
                {
                    if(helper(s.substring(j,i),wordDict)&&dp[j])
                    {
                        dp[i]=true;
                        break;
                    }
                }
            }
        }
        return dp[n];
    }
     public boolean helper(String s,List<String> wordDict)
    {
        for(String str:wordDict)
        {
            if(str.equals(s))
                return true;
        }
        return false;
    }
}

posted @ 2019-09-09 21:40  小路不会迷路  阅读(346)  评论(0编辑  收藏  举报