0

I have been given a problem to write a recursive function which uses Pascal's Rule. I completed the function and it is working, however, I know it can be improved using memoization. I'm not too sure how to go about this as it is my first time implementing memoization. Any help would be appreciated! Here is my code:

long choose(int n, int k) {
    if (k == 0 || n == k) {
        return 1;
    }
    else {
        return choose(n - 1, k) + choose(n - 1, k - 1);
    }
}

And here is how I am testing it:

int main(int argc, char **argv) {
    int n = atoi(argv[1]);
    int k = atoi(argv[2]);
    printf("%ld \n", choose(n, k));
}
3
  • You can use a global 2-dimensional array that maps n and k to the value returned by the function. Commented Nov 9, 2020 at 21:50
  • You can notice that choose(n, k) will calculate choose(n - 1, k - 1) and will call choose(n - 1, k) which is also will calculate choose(n - 1, k - 1). So it is calculated at least twice - meaning it is the subject for optimization by memoization. Commented Nov 9, 2020 at 21:51
  • I think any time things are calculated more than once it is worth considering. For n=10, k=5 many of the items are calculated 35 or even 70 times: onlinegdb.com/HJ6YzSPKw The memoization drops the number of function calls from 503 to 51: onlinegdb.com/HJF7rHDtw Commented Nov 9, 2020 at 22:39

1 Answer 1

1

If this is an exercise for a class where you're learning about recursion, then yes you can "improve" it by memoization. However, this is just a band-aid on the underlying grossly inefficient algorithm. If you find yourself using recursion, you're either attacking the problem the wrong way, or you're dealing with a really hard problem that has no efficient solution. Recursive relationships are useful as mathematical identities for proving properties by induction. They're not useful as implementation strategies. Sadly this is not taught well in most CS programs.

In the case of implementing "n choose k", Pascal's triangle is just the wrong way to implement it. Instead you use Pascal's triangle to develop the closed-form formula in terms of factorial, then implement that with a loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.