Hi I was working on some of the dynamic programming problems and I was wondering what you thought of the following solution for finding the combinations.
#include <iostream>
#include <vector>
using namespace std;
int find_combinations(int n, int k) {
k = k > (n/2) ? n-k : k;
vector<int> comb(k+1, 1);
for(int i = 1; i < int(comb.size()); ++i) {
comb[i] = (n * comb[i-1]) / i;
n--;
}
return comb[k];
}
int main() {
cout << find_combinations(50,6) << endl;
return 0;
}
I believe this solution will run in O(k) time and space complexity. I am using the property of combinations where 9 choose 7 is equivalent to 9 choose 2 to keep the space complexity at O(k). For the time complexity if we analyze the combinations formula we have something like this:
For 9 choose 1 we have
9 / 1
For 9 choose 2 we have
(9 * 8) / (2 * 1) -> we can see that we already computed the 9/1 in the previous combination and use it instead.
And the same follows for 9 choose 3 and so on.
(9 * 8 * 7) / (3 * 2 * 1)
Let me know what you think about this solution!
Best,
Luis