Novice Diary-January 22
What is recursion?
Is to keep calling itself
- 1. Finding repetitions: Finding subproblems such as finding the factorial of n is-finding the factorial of n-1
- 2. Find change: the amount of change as a parameter
- 3. Find the border: when does the exit end?
Case 1: Find the factorial of n
//1.求阶乘
static int f1(int n){
if (n == 1){
return 1;
}
return n * f1(n - 1);
}
public class 递归基础练习 {
public static void main(String[] args) {
System.out.println(f1(3));
}
Case 2: Print i — j
//2.打印i--j
static void f2(int i,int j){
if (i > j){
return;
}
System.out.println(i);
f2(i + 1,j);
}
public class 递归基础练习 {
public static void main(String[] args) {
f2(1,10);
}
Case 3: Find the sum of arrays
static int f3(int[] arr,int index){
if (index == arr.length - 1){
return arr[index];
}
return arr[index] + f3(arr,index + 1);
}
public class 递归基础练习 {
public static void main(String[] args) {
System.out.println(f3(new int[]{
1,2,3,4,5,6,7,8,9,10},0));
}
Case 4: string flip
static String f4(String src,int index){
if (index == 0){
return "" + src.charAt(0);
}
return src.charAt(index) + f4(src,index - 1);
public class 递归基础练习 {
public static void main(String[] args) {
System.out.println(f4("abcdefg",6));
}