Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit73e0594

Browse files
committed
Added bottom up approach
1 parent0d4cfba commit73e0594

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

‎Dynamic Programming/Fibonacci.java

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ public static void main(String[] args) throws Exception {
1818
BufferedReaderbr =newBufferedReader(newInputStreamReader(System.in));
1919
intn =Integer.parseInt(br.readLine());
2020

21-
System.out.println(fib(n));// Returns 8 for n = 6
21+
System.out.println(fibMemo(n));// Returns 8 for n = 6
22+
System.out.println(fibBotUp(n));// Returns 8 for n = 6
2223
}
2324

2425
/**
@@ -28,7 +29,7 @@ public static void main(String[] args) throws Exception {
2829
* Outputs the nth fibonacci number
2930
**/
3031

31-
publicstaticintfib(intn) {
32+
publicstaticintfibMemo(intn) {
3233
if (map.containsKey(n)) {
3334
returnmap.get(n);
3435
}
@@ -45,5 +46,30 @@ public static int fib(int n) {
4546

4647
returnf;
4748
}
49+
50+
/**
51+
* This method finds the nth fibonacci number using bottom up
52+
*
53+
* @param n The input n for which we have to determine the fibonacci number
54+
* Outputs the nth fibonacci number
55+
**/
56+
57+
publicstaticintfibBotUp(intn) {
58+
59+
Map<Integer,Integer>fib =newHashMap<Integer,Integer>();
60+
61+
for (inti=1;i<n+1;i++) {
62+
intf =1;
63+
if (i<=2) {
64+
f =1;
65+
}
66+
else {
67+
f =fib.get(i-1) +fib.get(i-2);
68+
}
69+
fib.put(i,f);
70+
}
71+
72+
returnfib.get(n);
73+
}
4874
}
4975

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp