【问题标题】:Recursive function to find combinations of elements in an array递归函数查找数组中元素的组合
【发布时间】:2017-07-13 03:20:18
【问题描述】:

我有一个更大的编程问题,需要我首先能够判断一个数组是否包含任何可以加起来达到目标​​值的元素组合。

我拥有的函数必须有以下标题:

bool sumCombination(const int a[], int size, int target);

函数必须使用递归,并且不能在其中任何地方使用任何 for 循环、while 循环或单词“goto”。此外,我不能使用任何辅助函数。

该函数如何工作的一些示例如下:

sumCombination([2, 4, 8], 3, 10) => true
sumCombination([2, 4, 8], 3, 12) => true
sumCombination([2, 4, 8], 3, 11) => false
sumCombination([], 0, 0)         => true

我不知道如何使用递归来解决这个问题,我曾与之合作过的每个人都告诉我,在给定的参数范围内似乎是不可能的。我已经使用循环解决了这个问题。但是,我试图完全通过递归来解决这个问题,而不使用任何循环。

如果有人能帮助我理解这个问题背后的逻辑,我将非常感激!

提前谢谢你!

【问题讨论】:

标签: c++ arrays function recursion


【解决方案1】:
bool sumCombination(const int a[], int size, int target) {
  // Can always add up to zero.
  if (!target) return true;
  // No elements to add up to anything.
  if (!size) return false;
  return
    // Try including the first element, see if tail adds up to the rest.
    sumCombination(a + 1, size - 1, target - a[0]) ||
    // Finally, try the tail alone, without the first element.
    sumCombination(a + 1, size - 1, target);
}

【讨论】:

  • 尾巴是什么意思?
  • 数组的所有元素都没有第一个。
  • @IgorTandetnik 现在的解决方案还不够。您需要旋转矢量size 次并重复尝试两个tail 组合。实际上,第一个示例 (sumCombination([2, 4, 8], 3, 10)) 将返回 false 而不是 true
  • 我也看不懂“||”。函数如何选择返回两个语句之一?
  • @Altairia 我可以谦虚地建议您阅读您最喜欢的 C++ 教科书中的逻辑运算符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2012-12-25
相关资源
最近更新 更多