我正在尝试实现一个类,该类将生成所有可能的无序n元组或组合,给定元素数量和组合大小。
换句话说,在调用以下内容时:
NTupleUnordered unordered_tuple_generator(3, 5, print);
unordered_tuple_generator.Start();
print() 是在构造函数中设置的回调函数。 输出应该是:
{0,1,2}
{0,1,3}
{0,1,4}
{0,2,3}
{0,2,4}
{0,3,4}
{1,2,3}
{1,2,4}
{1,3,4}
{2,3,4}
到目前为止,这是我所拥有的内容:
class NTupleUnordered {
public:
NTupleUnordered( int k, int n, void (*cb)(std::vector<int> const&) );
void Start();
private:
int tuple_size; //how many
int set_size; //out of how many
void (*callback)(std::vector<int> const&); //who to call when next tuple is ready
std::vector<int> tuple; //tuple is constructed here
void add_element(int pos); //recursively calls self
};
这是递归函数的实现,Start()只是一个启动函数,以便拥有更清晰的界面,它仅调用add_element(0)函数。
void NTupleUnordered::add_element( int pos )
{
// base case
if(pos == tuple_size)
{
callback(tuple); // prints the current combination
tuple.pop_back(); // not really sure about this line
return;
}
for (int i = pos; i < set_size; ++i)
{
// if the item was not found in the current combination
if( std::find(tuple.begin(), tuple.end(), i) == tuple.end())
{
// add element to the current combination
tuple.push_back(i);
add_element(pos+1); // next call will loop from pos+1 to set_size and so on
}
}
}
如果我想生成所有固定大小为N的可能组合,比如大小为3的组合,可以这样做:
for (int i1 = 0; i1 < 5; ++i1)
{
for (int i2 = i1+1; i2 < 5; ++i2)
{
for (int i3 = i2+1; i3 < 5; ++i3)
{
std::cout << "{" << i1 << "," << i2 << "," << i3 << "}\n";
}
}
}
如果N不是一个常量,你需要一个递归函数来模拟上述函数,通过在它自己的框架中执行每个for循环。当for循环终止时,程序返回到先前的框架,换句话说,回溯。我总是遇到递归问题,现在我需要将其与回溯相结合以生成所有可能的组合。有什么错误之处吗?我应该做什么或者我忽略了什么?
P.S:这是一个大学作业,还包括为有序n元组做基本相同的事情。
提前感谢!
/////////////////////////////////////////////////////////////////////////////////////////
只是想跟进正确的代码,以防其他人也想知道同样的事情。
void NTupleUnordered::add_element( int pos)
{
if(static_cast<int>(tuple.size()) == tuple_size)
{
callback(tuple);
return;
}
for (int i = pos; i < set_size; ++i)
{
// add element to the current combination
tuple.push_back(i);
add_element(i+1);
tuple.pop_back();
}
}
对于有序n元组的情况:
void NTupleOrdered::add_element( int pos )
{
if(static_cast<int>(tuple.size()) == tuple_size)
{
callback(tuple);
return;
}
for (int i = pos; i < set_size; ++i)
{
// if the item was not found in the current combination
if( std::find(tuple.begin(), tuple.end(), i) == tuple.end())
{
// add element to the current combination
tuple.push_back(i);
add_element(pos);
tuple.pop_back();
}
}
}
感谢Jason提供详尽的回答!
pos
只是您的tuple
向量的大小,因此您应该使用tuple.size()
。 - howardtuple.size()
是正确的,感谢指出。 - Lechuzza