leetCode解题报告5道题(五)

题目一:

Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and  sum = 22 ,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

分析:题意为给你一个数sum,求是否有从root结点到某个叶子结点的和等于数sum的路径,如果有的话,返回true,否则返回false;

AC代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        /*如果root == null直接返回false*/
        if (root == null){
            return false;
        }
        /*sum 减去当前root的值*/
        sum -= root.val;
        /*如果已经到了叶子结点,判断sum是否已经减到了0*/
        if (root.left == null && root.right == null && sum == 0){
            return true;
        }
        /*flag的话,要判断左右子树是否有路径可以满足,即为
          
        */
        boolean flag = hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
        return flag;
    }
}


Path Sum II

 (姐妹题)

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and  sum = 22 ,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]


分析:无情递归就OK了,递归结束的条件:当是叶子结点并且sum的值已经变成了0,这时候的List为一组有效的解,加入到结果集合result中。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * CSDN: 胖虎 http://blog.csdn.net/ljphhj
 */
public class Solution {
    private ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        if (root == null){
            return result;
        }
        
        calPath(root, sum, new ArrayList<Integer>());
        return result;
    }
    
    public void calPath(TreeNode root, int sum, ArrayList<Integer> list){
        sum -= root.val;
        list.add(root.val); //当前值加入“可能的解”集合list中
        /*如果为叶子结点了,那么就判断是否sum已经等于0了,如果等于0则为一个有效解*/
        if (root.left == null && root.right == null && sum == 0){
            result.add(list);
            return ;
        }
        /*如果不是叶子结点,则继续往左右子树找*/
        if (root.left != null){
            calPath(root.left, sum, new ArrayList<Integer>(list));
        }
        if (root.right != null){
            calPath(root.right, sum, new ArrayList<Integer>(list));
        }
    }
}


题目二:

Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m andn respectively.

分析:给我们A数组(长度:m)和B数组(长度: n),A数组足够大,有m+n的空间,那么我们采用从尾向前的方法往A数组中添加值,这样复杂度O(m+n)

AC代码:

public class Solution {
    public void merge(int A[], int m, int B[], int n) {
        if (m == 0){
            for (int i=0; i<n; ++i){
                A[i] = B[i];
            }
            return ;
        }
        if (n == 0){
            return ;
        }
        
        int pA = m-1;
        int pB = n-1;
        int pIndex = m+n-1;
        /*从尾向前添加数字*/
        while (pA >= 0 && pB >= 0){
            if (B[pB] > A[pA]){
                A[pIndex--] = B[pB--];
            }else{
                A[pIndex--] = A[pA--];
            }
        }
        /*pA>=0不处理,因为本来就在A数组中*/
        /*如果循环结束了,pB>=0则表示B数组还有值没加入到A数组中*/
        while (pB >= 0){
            A[pIndex--] = B[pB--];   
        }
    }
}


题目三:

Symmetric Tree(对称树)

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following is not:

    1
   / \
  2   2
   \   \
   3    3

分析:题目给我们一个二叉树的结构,让我们去判断这个二叉树是否是对称的。这道题目可以有两种做法,递归(424ms)或者用层次遍历树(524ms)的方法

这个题目的递归很容易就看出来了,我就不详细讲,具体看代码里面的注释理解!

(递归)AC代码(424ms):

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    /*判断左右子树是否对称*/
    public boolean checkSymmetric(TreeNode lsubTree,TreeNode rsubTree){
        /*几种基本情况的排除*/
        if(lsubTree==null && rsubTree==null) 
            return true;
        else if(lsubTree!=null && rsubTree==null) 
            return false;
        else if(lsubTree==null && rsubTree!=null) 
            return false;
        else if(lsubTree.val != rsubTree.val) 
            return false;
        
        /*再递归看下子树是否对称,只有子树也对称了才可以*/
        boolean lt=checkSymmetric(lsubTree.left, rsubTree.right);
        boolean rt=checkSymmetric(lsubTree.right, rsubTree.left);
        return lt && rt;
    }
    /*只要左右子树对称那么整个二叉树就对称了*/
    public boolean isSymmetric(TreeNode root) {
        if(root==null) 
            return true;
        return checkSymmetric(root.left,root.right);
    }
}


(层次遍历)AC代码(524ms):

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        if (root == null)
            return true;
        /*加入根结点的左右子结点*/
        queue.add(root.left);
        queue.add(root.right);
        /*层次遍历*/
        while (queue.size() != 0){
            String s = new String("");
            ArrayList<TreeNode> list = new ArrayList<TreeNode>();
            /*把一层的结点都取出来之后放入list集合*/
            while (queue.size() != 0){
                TreeNode node = queue.remove();
                list.add(node);
            }
            /*把这一层的结点对应的值转换成字符串*/
            for (int i=0;i<list.size(); ++i){
                TreeNode node = (TreeNode)list.get(i);
                if (!s.equals("")){
                    s += " ";
                }
                if (node != null)
                    s += node.val;
                else
                    s += "Null";
                if (node != null){
                queue.add(node.left);
                queue.add(node.right);
                }
            }
            /*判断这一层的结点转换成的字符串是否满足条件,不满足直接return*/
            if (!isManZu(s))
                return false;
        }
        
        return true;
    }
    /*检测字符串是否满足条件*/
    public boolean isManZu(String s){
        String[] arrays = s.trim().split(" ");
        int len = arrays.length;
        if (len % 2 == 1)
        	return false;
        for(int i=0; i<len/2; ++i){
            if (!arrays[i].equals(arrays[len-1-i]))
                return false;
        }
        return true;
    }
}


题目四:

Flatten Binary Tree to Linked List

 

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6


分析:仔细观察题目给出的例子,不难发现其实这个可以用递归来做,求root结点的flatten tree相当于先求出左子树,再求出右子树,然后将左子树的最后一个结点连接到右子树的第一个结点,将root的右子树连接到左子树的第一个结点上,总而言之这题还是比较简单的,建议做这题的时候可以在纸上画一下图,帮助理解!

情况:

1、root只有左子树

2、root只有右子树

3、root左右子树都有


AC代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        transform(root);
        return ;
    }
    public TreeNode transform(TreeNode root){
        if (root == null)
            return null;
        if (root.left == null && root.right == null)
            return root;
        TreeNode leftChild = null;
        TreeNode rightChild = null;
        if (root.left != null){
            leftChild = transform(root.left);
        }
        if (root.right != null){
            rightChild = transform(root.right);
        }
        if (leftChild != null){
            leftChild.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        if (rightChild != null)
            return rightChild;
        if (leftChild != null)
            return leftChild;
        return root;
    }
}


题目五:

Distinct Subsequences

 

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit"T = "rabbit"

Return 3.

题意:求出字符串T在字符串S中出现的次数,


S字符串:

0 1  2  3  4  5  6

r  a  b  b  b  i   t


T字符串:

0 1  2  3  4   5 

r  a  b  b  i   t


出现的最大次数是3,三种情况分别为:

S: 0 1 2 3 5 6

S: 0 1 2 4 5 6

S: 0 1 3 4 5 6

这样子,我们很容易知道这其实是一个DP的问题

对应的状态转移方程式

if(S[i] == T[j])
	dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
else
	dp[i][j] = dp[i-1][j];


AC代码:

public class Solution {
    public int numDistinct(String S, String T) {
        int n = S.length();
        int m = T.length();
        if (m > n)
            return 0;
        int[][] results = new int[n+1][m+1];
        for (int i=0; i<n+1; ++i){
            results[i][0] = 0;
        }
        for (int i=0; i<m+1; ++i){
            results[0][i] = 0;
        }
        
        for (int i=1; i<n+1; ++i){
            for (int j=1; j<m+1; ++j){
                results[i][j] = results[i-1][j];
                if (S.charAt(i-1) == T.charAt(j-1)){
                    if (j == 1)
                        results[i][j] += 1;//j == 1的话表示第一个字符,直接加1
                    else
                        results[i][j] += results[i-1][j-1];
                }
            }
        }
        return results[n][m];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值