【发布时间】:2013-10-11 21:54:02
【问题描述】:
我有 n 个元素存储在一个数组中,并且在 n(n 选择了 k) 上可能有 k 个子集。 我必须在长度为 n 的数组中找到 k 个元素的所有可能组合,并且对于每个集合(长度为 k),对所选元素进行一些计算。
我已经编写了一个递归算法(在 C++ 中),它工作得很好,但是对于大量它会崩溃并超出堆空间。
我该如何解决这个问题?如何计算所有 n 的集合,为大 n 和 k 选择 k? 有任何 C++ 库可以帮助我吗?
我知道这是一个 np 问题,但我会编写最好的代码来计算可能的最大数字。
哪个是最大的数字(n 和 k),超过它变得不可行?
我只要求最好的算法,而不是不可行的空间/工作。
这是我的代码
vector<int> people;
vector<int> combination;
void pretty_print(const vector<int>& v)
{
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void go(int offset, int k)
{
if (k == 0) {
pretty_print(combination);
return;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1);
combination.pop_back();
}
}
int main() {
int n = #, k = #;
for (int i = 0; i < n; ++i) { people.push_back(i+1); }
go(0, k);
return 0;
}
【问题讨论】:
-
“n 选择了 k”是什么意思?请更清楚地说明您必须计算什么组合
-
您可能想要使用帕斯卡三角形的属性:en.wikipedia.org/wiki/Pascal's_triangle
-
组合不正是 OP 所需要的吗?
-
@computer 一组 n 个元素中 k 个元素的所有子集。 en.wikipedia.org/wiki/Combination
标签: c++ arrays algorithm combinations