-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursiveAlgorithm.java
More file actions
89 lines (73 loc) · 1.67 KB
/
recursiveAlgorithm.java
File metadata and controls
89 lines (73 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package algorithm;
/**
* @author zhongshanhuang
* @company caih
* @email [email protected]
* @create 2019-08-08 16:03
*/
public class recursiveAlgorithm {
public static void main(String[] args) {
//1
// Test t= new Test();
// t.test(4);
//2
// Factorial factorial = new Factorial();
// int res = factorial.factorial(3);
// System.out.println(res);
FiBoNaqiNum fiBoNaqiNum = new FiBoNaqiNum();
int n = fiBoNaqiNum.fib(5);
System.out.println(n);
}
}
/**
* 1
*/
class Test{
public void test(int n){
System.out.println("n前 = " + n);
if(n > 2){
test(n - 1); //被调用的地方的上部分已经执行,而后部分没有被执行
}
System.out.println("n后 = " + n);
// 输出:
// n前 = 4
// n前 = 3
// n前 = 2
// n后 = 2
// n后 = 3
// n后 = 4
//*******************************
// System.out.println("n前 = " + n);
// if(n > 2){
// test(n - 1); //被调用的地方的上部分已经执行,而后部分没有被执行
// }else{
// System.out.println("n后 = " + n);
// }
// 输出:
// n前 = 4
// n前 = 3
// n前 = 2
// n后 = 2
}
}
/**
* 2
*/
class Factorial{
public int factorial(int n){
if (n == 1){
return 1;
}else{
return n*factorial(n-1);
}
}
}
class FiBoNaqiNum{
public int fib(int n){
if(n == 1 || n == 0){
return 1;
}else{
return fib(n - 2) + fib(n - 1);
}
}
}