Skip to content

Added Fibanacci using memoization #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 10, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Added bottom up approach
  • Loading branch information
varunu28 committed Sep 4, 2017
commit 73e05940eae0a46fa4921ef1ecfb81fab4f91a76
30 changes: 28 additions & 2 deletions Dynamic Programming/Fibonacci.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());

System.out.println(fib(n)); // Returns 8 for n = 6
System.out.println(fibMemo(n)); // Returns 8 for n = 6
System.out.println(fibBotUp(n)); // Returns 8 for n = 6
}

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

public static int fib(int n) {
public static int fibMemo(int n) {
if (map.containsKey(n)) {
return map.get(n);
}
Expand All @@ -45,5 +46,30 @@ public static int fib(int n) {

return f;
}

/**
* This method finds the nth fibonacci number using bottom up
*
* @param n The input n for which we have to determine the fibonacci number
* Outputs the nth fibonacci number
**/

public static int fibBotUp(int n) {

Map<Integer,Integer> fib = new HashMap<Integer,Integer>();

for (int i=1;i<n+1;i++) {
int f = 1;
if (i<=2) {
f = 1;
}
else {
f = fib.get(i-1) + fib.get(i-2);
}
fib.put(i, f);
}

return fib.get(n);
}
}