今日学习
IDEA使用
1.一键生成getter和setter
选中属性右击Generate
2.与替换相关
重命名文件、方法、属性等(rename):SHIFT+F6
重构类、方法(change signarture):CTRL+F6
ctrl + r: 当前文件内容替换,指的是在当前打开的文件中替换匹配的字符,只操作一个文件。
ctrl + shift + r: 在路径中替换,指的是在选定的目录下或者类包下,查找要被替换的字符,再在第二个输入框中输入要替换的字符,点击弹出框的右下角的replace或者replaceall即可
一、递归与分治
1. 什么是递归
某个函数直接或间接地调用自身,将原问题地求解转换为许多性质相同,但规模更小的子问题。
求解时只需要关注如何把原问题划分为符合条件的子问题,而不需要过分关注这个子问题时如何被解决的。
递归代码最重要的两个特征:结束条件和自我调用。
自我调用是在解决子问题;结束条件定义了最简子问题的答案。
int fun(传入数值){
if(终止条件)
return 最小子问题的解;
return func 缩小规模;
}
2. 递归的缺点:
递归时利用堆栈来实现的。每当进入一个函数调用,栈就会增加一层栈帧,每次函数返回,栈就会减少一层栈帧。而栈不是无限大的,当递归层数过多,就会造成栈溢出的后果。
3.实例
给一课二叉树,和一个目标值,节点上的值有正有负,返回树中和等于目标值的路径条数,让你编写 pathSum 函数:
/* 来源于 LeetCode PathSum III: https://leetcode.com/problems/path-sum-iii/ */
root = [10,5,-3,3,2,null,11,3,-2,null,1],
sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths that sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
编码时的注意事项:在java中,int型数组不能赋值为空,int数组在定义时就已经被默认初始化为0;要想达到类似效果,可以将int数组转为Integer数组。
sorry。在此之前,让我们先来复习一下二叉树
package com.seu.recursion;
/**
* @author SJ
* @date 2020/9/25
*/
public class Node {
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
private int data;
public Node getLeftChild() {
return leftChild;
}
public void setLeftChild(Node leftChild) {
this.leftChild = leftChild;
}
private Node leftChild;
public Node getRightChild() {
return rightChild;
}
public void setRightChild(Node rightChild) {
this.rightChild = rightChild;
}
private Node rightChild;
public Node(int data) {
this.data = data;
this.leftChild = null;
this.rightChild = null;
}
}
package com.seu.recursion;
/**
* @author SJ
* @date 2020/9/25
*/
public class Tree {
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
private Node root;
public Tree(int[] nums, int index) {
this.root = createTree(nums, index);
}
public Node createTree(int[] nums, int index) {
Node node = null;
if (index < nums.length) {
node = new Node(nums[index]);//每次进来先建节点
node.setLeftChild(createTree(nums, index * 2 + 1));
node.setRightChild(createTree(nums, index * 2 + 2));