Skip to content

Instantly share code, notes, and snippets.

@xiaq
Last active February 14, 2017 20:52
Show Gist options
  • Select an option

  • Save xiaq/d55d40f530384243df15a74e9722aacc to your computer and use it in GitHub Desktop.

Select an option

Save xiaq/d55d40f530384243df15a74e9722aacc to your computer and use it in GitHub Desktop.
Recursion vs Dynamic Programming

Recursive function:

int fib(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return fib(n-1) + fib(n-2);
}

Time complexity is O(fib(n)). The derivation is left as an exercise to the reader.

Dynamic programming version:

int fib(int n) {
    int a[n+1];
    a[0] = a[1] = 1;
    for (int i = 2; i <= n; i++) {
        a[i] = a[i-1] + a[i-2];
    }
    return a[n];
}

Time complexity is O(n).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment