Created
January 9, 2015 03:04
-
-
Save vgmoose/6ae367cd08fd4534553b to your computer and use it in GitHub Desktop.
dynamic programming solution to fibonacci sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class fib | |
{ | |
public static void main(String[] args) | |
{ | |
System.out.println(fib(5)); | |
} | |
public static int fib(int x) | |
{ | |
// create an array of size x | |
int[] dp = new int[x+1]; | |
// base case | |
dp[0] = 0; | |
dp[1] = 1; | |
for (int i=2; i<=x; i++) | |
// update based on the last two | |
dp[i] = dp[i-1] + dp[i-2]; | |
return dp[x]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment