码迷,mamicode.com
首页 > 其他好文 > 详细

从递归到memo到动态规划

时间:2019-09-09 22:49:33      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:equal   boolean   false   bsp   递归   动态规划   int   lse   n+1   

//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到动态规划

标签:equal   boolean   false   bsp   递归   动态规划   int   lse   n+1   

原文地址:https://www.cnblogs.com/cold-windy/p/11494445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!