【发布时间】:2018-11-15 22:22:15
【问题描述】:
我正在尝试使用递归和记忆来计算 nck 组合问题。它适用于小输入。但是,对于大量输入,它会失败。
ans = n! / ( (n-k)! * k!)
对于 8C3,答案是 56。[工作中]
对于 156C12,预期输出为 281014969393251275 [不工作]
如何扩展或优化它?
点击此处运行代码:http://cpp.sh/9ijiy
#include <iostream>
#include <map>
using namespace std;
long long int calls=0; // I know global vars are bad, but, i'm only using it for checking number of recursive calls
long long int fact(int n)
{
calls++;
static map<int, long long int> cache = {{0,1},{1,1}}; // factorial of 0 and 1 is 1
if(cache.find(n) == cache.end()) // if n is NOT found
{
long long int ans = (long long int)n*fact(n-1);
cache.insert(pair<int, long long int>(n,ans));
}
return cache[n];
}
long long int combin(int n, int k)
{
return fact(n)/(fact(n-k)*fact(k));
}
int main()
{
calls=0; cout << "8C3 is " << combin(8,6) << endl;
cout << "Number of calls is " << calls << endl;
calls=0; cout << "156C12 is " << combin(156,12) << endl;
cout << "Number of calls is " << calls << endl;
return 0;
}
【问题讨论】:
标签: c++ memoization