我得到了这行代码,它弹出数组的一个整数,将其保存到 int element
,然后将其从数组中删除。然后在 return 语句 return CountCriticalVotes(rest, blockIndex + element);
中将它添加到 blockIndex
变量中,如果它在数组为空之前达到 10,则返回 1。但我的问题是,我不希望它把参数数组中的所有值加起来,而是只加一个然后将参数值恢复到原来的状态,然后添加一个新的,恢复等。 . 我该怎么做?
int NumCriticalVotes :: CountCriticalVotes(Vector<int> & blocks, int blockIndex)
{
if (blockIndex >= 10)
{
return 1;
}
if (blocks.isEmpty())
{
return 0;
} else {
int element = blocks.get(0);
Vector<int> rest = blocks;
rest.remove(0);
return CountCriticalVotes(rest, blockIndex + element);
最佳答案
递归地做(顺便说一句,效率很低。没有理由这样做):
bool NumCriticalVotes :: CountCriticalVotes(Vector<int> const& blocks,
int blockIndex,
size_t current = 0)
{
// check if we reach the end of the vector
if (current == block.size())
{
return true;
}
int sum = blockIndex+block.get(current);
if (sum >= 10)
{
return true;
}
return CountCriticalVotes(blocks, blockIndex, current+1);
}
关于c++ - 递归:使用传入参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13813930/