【问题标题】:Why does this code return an empty array?为什么这段代码返回一个空数组?
【发布时间】:2020-01-19 05:29:32
【问题描述】:

问题:给定一个不同整数的集合,返回所有可能的排列。

示例:输入:[1,2,3]

期望的输出: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

在 JavaScript 中数组不是通过引用传递的吗?为什么我返回结果数组是空的?

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
  var result = [];
  helper(nums, result, []);
  return result;
};

var helper = function(nums, result, cur) {
  if (cur.length == nums.length) {
    result.push(cur);
  } else {
    for (let i = 0; i < nums.length; i++) {
      cur.push(nums[i]);
      helper(nums, result, cur);
      cur.pop();
    }
  }
}
console.log(permute([1, 2, 3]));

【问题讨论】:

    标签: javascript algorithm recursion data-structures permutation


    【解决方案1】:

    当您调用 helper 时,您只会创建一个 cur 数组:

    helper(nums, result, []);
    

    你在helper中进行变异和递归传递。内存中只有一个数组;到最后,您已经.popped 数组中的最后一项,result 数组中的每一项都指向同一个对象,现在是空的cur 数组。

    相反,在循环中克隆cur,这样当/如果它被推送时,您将推送一个 new 数组,而不是对将在任何地方重用的旧数组的引用:

    for (let i = 0; i < nums.length; i++) {
      const temp = cur;
      cur = [...cur, nums[i]]; // Similar to `.push`, except it creates a new array
      helper(nums, result, cur);
      cur = temp; // Similar to `.pop` - reverts the array to what it was originally
    }
    

    var permute = function(nums) {
      var result = [];
      helper(nums, result, []);
      return result;
    };
    
    var helper = function(nums, result, cur) {
      if (cur.length == nums.length) {
        result.push(cur);
      } else {
        for (let i = 0; i < nums.length; i++) {
          const temp = cur;
          cur = [...cur, nums[i]]; // Similar to `.push`, except it creates a new array
          helper(nums, result, cur);
          cur = temp; // Similar to `.pop` - reverts the array to what it was originally
        }
      }
    }
    
    console.log(permute([1, 2, 3]));

    【讨论】:

      【解决方案2】:

      不,JavaScript 中的所有内容都是按值传递的。在您的函数helper 中,将创建一个局部变量result,然后在调用helper 时为其分配参数值。您最可能想做的是:result = helper(nums, result, []);

      【讨论】:

      • "JavaScript 中的一切都是按值传递的。"从技术上讲,这是真的。但是为非原始参数复制和传递的值是对基础项的引用。所以调用者和被调用者有两个不同的引用,每个都指向同一个值。换句话说,helper 中的 result 变量是(除非重新分配)对 permute 中使用的引用 result 所引用的同一项目的引用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多