美文网首页我是程序员互联网科技程序员
leetcode算法题解(Java版)-16-动态规划(单词包含

leetcode算法题解(Java版)-16-动态规划(单词包含

作者: 阿里云云栖号 | 来源:发表于2018-05-25 11:59 被阅读226次

    摘要: 碰到二叉树的问题,差不多就是深搜、广搜,递归那方面想想了,当然如果要考虑一下空间、时间,还需要进行剪枝和压缩处理。这题比较简单:判断两个树是否相等,可以递归的判断子树是否相等,最后找到边界条件就是是否都为空,都不为空时节点里面的值是否相等。

    一、递归

    题目描述

    Given two binary trees, write a function to check if they are equal or not.
    Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

    思路

    碰到二叉树的问题,差不多就是深搜、广搜,递归那方面想想了,当然如果要考虑一下空间、时间,还需要进行剪枝和压缩处理。这题比较简单:判断两个树是否相等,可以递归的判断子树是否相等,最后找到边界条件就是是否都为空,都不为空时节点里面的值是否相等。

    代码

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p==null&&q==null){
               return true;
            }
            else if(p==null||q==null){
                return false;
            }
            else if(q.val!=p.val){
                return false;
            }
            else{
                return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
            }
        }
    }
    

    二、动态规划

    题目描述

    Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
    For example, given
    s ="leetcode",
    dict =["leet", "code"].
    Return true because"leetcode"can be segmented as"leet code".

    思路

    dp的题目,写了几道了。核心无非就是确定dp数组和状态转移方程。这几道题都有明显的特点,那就是dp数组记录的就是所求的答案,所以答案一般都是dp[s.length()]这种形式的。

    有了上面的总结,再来看着道题目。要求一串字母是否可以由所给的字典中的单词拼出来,要求返回布尔型。那好,也同时提示我们了dp数组就是记录它的子串是否能满足要求,类型是布尔型:dp[i]表示的是s[0,i-1]这个子串能否满足要求。

    dp[i]=dp[j]&&s[j,i]是否在字典中(0<=j<=i-1)

    代码

    import java.util.Set;
    
    public class Solution {
        public boolean wordBreak(String s, Set<String> dict) {
            if(s==null||s.length()==0||dict==null||dict.size()==0){
                return false;
            }
            boolean [] dp = new boolean [s.length()+2];
            dp[0] = true;
            
            for(int i=1;i<=s.length();i++){
                for(int j=i-1;j>=0;j--){//从尾部扫描单词
                    if(dp[j]==true&&dict.contains(s.substring(j,i))){
                        dp[i]=true;
                        break;
                    }
                    else{
                        dp[i]=false;
                    }
                }
            }
            return dp[s.length()];
        }
    }
    

    三、深搜

    题目描述

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
    Return all such possible sentences.
    For example, given
    s ="catsanddog",
    dict =["cat", "cats", "and", "sand", "dog"].
    A solution is["cats and dog", "cat sand dog"].

    思路

    题目是上一道题的加强版,为了考察动态规划。感觉有点复杂,没想出来怎么在上一道的基础上改进。
    深搜可以解决问题!直接看代码了

    代码

    import java.util.ArrayList;
    import java.util.Set;
    
    public class Solution {
        public ArrayList<String> res = new ArrayList<>();
        public ArrayList<String> wordBreak(String s, Set<String> dict) {
             dfs(s,s.length(),dict,"");
            return res;
        }
        public void dfs(String s,int index,Set<String> dict,String temp){
            if(index==0){
                if(temp.length()>0){
                    res.add(temp.substring(0,temp.length()-1));//如果写成res.add(temp)则末尾会多一个空格,小细节
                }
            }
            for(int i=index-1;i>=0;i--){
                if(dict.contains(s.substring(i,index))){
                    dfs(s,i,dict,s.substring(i,index)+" "+temp);
                }
            }
        }
    }
    

    本文作者:kissjz
    阅读原文
    本文为云栖社区原创内容,未经允许不得转载。

    相关文章

      网友评论

      本文标题:leetcode算法题解(Java版)-16-动态规划(单词包含

      本文链接:https://www.haomeiwen.com/subject/zivyjftx.html