算法题存档20190401

本文探讨了帕斯卡三角的生成算法及其优化,同时深入研究了二叉树相关的问题,包括路径求和及节点连接等,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an index k, return the k th row of the Pascal's triangle.

For example, given k = 3,
Return[1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> prev = new ArrayList<>();
        Integer numRows = rowIndex + 1;
        for(int i = 1; i < numRows + 1; i++) {
            Integer num = 0;
            ArrayList<Integer> list = new ArrayList<>();
            list.add(1);
            num++;
            while(num < i + 1) {
                if(num == i) {
                    break;
                } else if(num == i - 1) {
                    list.add(1);
                } else {
                    list.add(prev.get(num) + prev.get(num - 1));
                }
                num++;
            }
            prev = list;
        }
       return prev;
    }
}

 

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
         ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        ArrayList<Integer> prev = new ArrayList<>();
        for(int i = 1; i < numRows + 1; i++) {
            Integer num = 0;
            ArrayList<Integer> list = new ArrayList<>();
            list.add(1);
            num++;
            while(num < i + 1) {
                if(num == i) {
                    break;
                } else if(num == i - 1) {
                    list.add(1);
                } else {
                    list.add(prev.get(num) + prev.get(num - 1));
                }
                num++;
            }
            prev = list;
            result.add(list);
        }

        return result;
    }
}

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

 

For example,
Given the following binary tree,

         1
       /  \
      2    3
     / \    \
    4   5    7

 

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
public class Solution {
    public void connect(TreeLinkNode root) {
       if(root == null) {
            return;
        }
        LinkedList<TreeLinkNode> queue = new LinkedList<>();
        LinkedList<TreeLinkNode> next = new LinkedList<>();
        queue.push(root);
        TreeLinkNode prev = null;
        while(!queue.isEmpty()) {
            TreeLinkNode node = queue.pop();
            if(node.left != null) {
                if(prev != null) {
                    prev.next = node.left;
                }
                prev = node.left;
                
                next.add(node.left);
            }
            if(node.right != null) {
                if(prev != null) {
                    prev.next = node.right;
                }
                prev = node.right;
                
                next.add(node.right);
            }
            if(node.next == null) {
                prev = null;
                queue = next;
                next = new LinkedList<>();
            }
        }
    }
}

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

 

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.

Initially, all next pointers are set toNULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

 

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

 

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL
/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;

public class Solution {
     public void connect(TreeLinkNode root) {
        if(root == null) {
            return;
        }
        LinkedList<TreeLinkNode> queue = new LinkedList<>();
        queue.push(root);
        TreeLinkNode newLevel = root.left;
        TreeLinkNode prev = null;
        while(!queue.isEmpty()) {
            TreeLinkNode node = queue.pop();
            if(node.equals(newLevel)) {
                newLevel = node.left;
                prev = null;
            }
            if(node.left == null) {
                break;
            } else {
                if(prev != null) {
                    prev.next = node.left;
                }
                prev = node.right;
                node.left.next = node.right;
                queue.add(node.left);
                queue.add(node.right);
            }
        }
    }
}

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 andsum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
public class Solution {
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();

        compute(root, sum, result, new ArrayList<>());

        return result;
    }
    
    public void compute(TreeNode root, int sum, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> temp) {
       if(root != null) {
            temp.add(root.val);
            if(root.left == null && root.right == null && (sum - root.val) == 0) {
                result.add(new ArrayList<>(temp));
                temp.remove(temp.size() - 1);
                return;
            }
            compute(root.left, sum - root.val, result, temp);
            compute(root.right, sum - root.val, result, temp);
            temp.remove(temp.size() - 1);
        }

    }
}

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 andsum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

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

/**
 * 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) {
         if(root != null) {
            if(root.left == null && root.right == null) {
                return (sum - root.val) == 0;
            }
           return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        }

        return false;
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值