javascript – 给定一个带数字的数组,如何编写一个递归函数,当2个元素加到目标时,它会在数组中找到索引?

这是提示:给定一个整数数组,返回两个数字的索引,使它们加起来到一个特定的目标.

您可以假设每个输入都只有一个解决方案.

例:
给定nums = [2,11,15,7],target = 9,

因为nums [0] nums [1] = 2 7 = 9,
返回[0,1].

这是我的解决方案,但它似乎没有给出我预期的输出:

var sumTarget = function(array, target) {
  var result = [];
  var copy = array.slice();
  var firstValue = array.shift();
  if (array.length === 0) {
    return result;
  }
  for (var i = copy.indexOf(firstValue) + 1; i < copy.length; i++) {
    if (firstValue + copy[i] === target) {
      Array.prototype.push.apply(result, [copy.indexOf(firstValue), i]);
    }
  }

  return sumTarget(array, target);
};

最佳答案 像这样的东西:

https://jsfiddle.net/rqp93gpy/2/

function getIndexes(arr, target, offset) {
  var result = [], i;
  if (arr.length <= 1) return [];

  if (offset === undefined) offset = 0;

  for (i = 1; i < arr.length; i++) {
    if (arr[0] + arr[i] === target) {
      result.push([offset, offset + i]);
    }
  }
  return result.concat(getIndexes(arr.slice(1), target, offset + 1));
}

console.log(JSON.stringify(getIndexes([2, 11, 15, 7, 6, 3, 4, 8, 9, 5, 7], 9),
                           null, 4));

输出:

[
    [
        0,
        3
    ],
    [
        0,
        10
    ],
    [
        4,
        5
    ],
    [
        6,
        9
    ]
]
点赞