一、递归
递归的思想:将大规模的问题变成小规模的问题,问题不变,规模变小。
递归的三要素:1、处理方法,方法自调来解决大规模的问题,提取相同的逻辑,缩小问题规模;
2、明确递归的终止条件;
3、给出递归终止的解决办法。
二、递归的经典例题
1、递归实现二分查找
public static int binarySearch(int[] list, int key){
if(list == null || list.length == 0){
return -1;
}
return binaySearchBrRecur(list, key, 0, list.length-1);
}
public static int binaySearchBrRecur(int[] list, int key, int low, int high){
if(low <= high){//提取重复逻辑,缩小问题规模
int mid = (low+high) >> 1;
if(list[mid] == key){
return mid;//明确递归终止条件并给出终止条件的解决办法
}else if(list[mid] > key){
return binaySearchBrRecur(list, key, low, mid-1);
}else{
return binaySearchBrRecur(list, key, mid+1, high);
}
}
return -1;
}
2、实现阶乘 n * n-1 * n-2 * ... * 2 * 1
public static long factorialByCircu(int n){
if( n < 0){
return 0;
}
long result = n;
while(n > 1){
n--;
result *= n;
}
return result;
}
3、实现斐波那契数列
public static int optimizingFibonacciByRecur(int n, int first, int second){
if(n <= 0) return 0;
if(n == 1){
return first;
}else if(n == 2){
return second;
}else if(n == 3){
return first + second;
}
return optimizingFibonacciByRecur(n-1, second, first+second);
}
4、递归去实现判断一个字符串是否是回文字符串
public static boolean isPlalindromeString(String s, int start, int end){
if(s == null || s.length() == 0 || start > end) return false;
if(start < end){
if(s.charAt(start) != s.charAt(end)){
return false;//递归的终止条件+解决办法
}else {
//缩小问题规模,提取重复逻辑
return isPlalindromeString(s, start+1, end-1);
}
}
return true;
}
5、实现汉诺塔问题
public static void hanoi(int num, char from, char transfer, char to){
if(num == 1){
System.out.println("move "+num+"号 "+from+" to "+to);
}else{
hanoi(num-1, from, to, transfer);
System.out.println("move "+num+"号 "+from+" to "+to);
hanoi(num-1, transfer, from, to);
}
}
6、实现杨辉三角
public static int pascalsTriangle(int x, int y)throws NoSuchFieldException{
if(x < y){
throw new NoSuchFieldException("illeagal row or col");
}
if(y == 0 || x == y){
return 1;
}
return pascalsTriangle(x-1, y-1) + pascalsTriangle(x-1, y);
}