简体   繁体   English

LeetCode 问题 113 - 为什么我们需要解构路径数组?

[英]LeetCode Question 113 - Why do we need to destructure the path array?

I was trying to complete this question on leetcode and I found a solution.我试图在 leetcode 上完成这个问题,我找到了解决方案。 Everything here makes sense to me except the part where they destructure the path array as "[...path]".除了将路径数组解构为“[...path]”的部分之外,这里的所有内容对我来说都是有意义的。 Can someone explain to me why we wouldn't just pass it as a regular array?有人可以向我解释为什么我们不将它作为常规数组传递吗?

Thank you in advance.先感谢您。

https://leetcode.com/problems/path-sum-ii/ https://leetcode.com/problems/path-sum-ii/

var pathSum = function(root, targetSum, sum = 0, path = [], result = []) {

   if(!root) return result;
    
    sum += root.val;
    path.push(root.val)
    
   if(!root.left && !root.right){
       if(sum === targetSum){
           result.push([...path])
       } else {
           path.pop()
       }
   }
   
   pathSum(root.left, targetSum, sum, [...path], result)
   pathSum(root.right, targetSum, sum, [...path], result)
    
   return result;

};

In JavaScript, variables contain references to arrays, not the whole array.在 JavaScript 中,变量包含对 arrays 的引用,而不是整个数组。 An assignment一个任务

path1 = path;

copies the reference, not the array.复制引用,而不是数组。 Both variables contain the same reference to the same array.两个变量都包含对同一数组的相同引用。 Modifying path1 also modifies path .修改path1也会修改path

The expression表达方式

[...path]

creates a shallow copy of path.创建路径的浅拷贝。 This is required in this code to avoid modifications of the same array on different recursion steps.在此代码中这是必需的,以避免在不同的递归步骤中修改相同的数组。 Each recursive call gets its own copy of the path.每个递归调用都有自己的路径副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM