-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursiveExample.java
More file actions
79 lines (67 loc) · 1.5 KB
/
RecursiveExample.java
File metadata and controls
79 lines (67 loc) · 1.5 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
package algo.recursion;
import java.util.HashMap;
import java.util.Map;
/**
* @author xiangdotzhaoAtwoqutechcommacom
* @date 2019/11/20
*/
public class RecursiveExample {
static Map<Integer, Integer> map = new HashMap<>();
public static int f(int n) {
if (n == 1) {
return 1;
}
return f(n - 1) + 1;
}
public static int fPerf(int n) {
int ret = 1;
for (int i = 2; i <= n; i++) {
ret++;
}
return ret;
}
public static int onStep(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return onStep(n - 1) + onStep(n - 2);
}
public static int onStepPer(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
if (map.containsKey(n)) {
return map.get(n);
}
int ret = onStep(n - 1) + onStep(n - 2);
map.put(n, ret);
return ret;
}
public static int onStepPerf(int n) {
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
int ret = 0;
int pre = 2;
int prePre = 1;
for (int i = 3; i <= n; i++) {
ret = pre + prePre;
prePre = pre;
pre = ret;
}
return ret;
}
public static void main(String[] args) {
System.out.println(f(11));
System.out.println(onStep(11));
}
}