从递归到memo到动态规划

Posted cold-windy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从递归到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;
   

以上是关于从递归到memo到动态规划的主要内容,如果未能解决你的问题,请参考以下文章

面试官问我斐波拉契数列,我从暴力递归讲到动态规划 ...

从暴力递归到动态规划,记忆化搜索

左程云-递归和动态规划

动态规划基础

从暴力递归到动态规划小乖,你也在为转移方程而烦恼吗?

数字三角形,从递归到动态规划