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));
}
nandkto the value returned by the function.choose(n, k)will calculatechoose(n - 1, k - 1)and will callchoose(n - 1, k)which is also will calculatechoose(n - 1, k - 1). So it is calculated at least twice - meaning it is the subject for optimization by memoization.