339. Nested List Weight Sum

Easy.

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)

Example 2:
Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27)

做这个题是做到Nested List Weight Sum ii的时候看到有人在讨论,没想到又暴露了自己基础知识的问题。

339. Nested List Weight Sum_第1张图片
Screen Shot 2017-10-19 at 5.13.31 PM.png

这种写法问题出在int传递参数的时候,是将传入的参数的具体值(基本数据类型)。所以形参接收并复制其具体的int值,在方法内部对int值进行了更改,直接反映到了其方法内部的变量内容上,对方法外部的实参是没有影响的。比如说这里,我们遇到[1,1]的时候,进入helper函数,计算出res = 2, 但接着遍历到2的时候,这个res又会回到本身的值res = 0, 所以res最后还是等于0.

下面这篇文章很好地解释了Java的传参方式:
Java传参方式

public class Solution {
    public int depthSum(List nestedList) {
        // Write your code here
        int depth = 1;
        int res = 0;
        helper(nestedList, depth, res);
        return res;
    }
    
    private void helper(List nestedList, int depth, int res){
        for (NestedInteger ni : nestedList){
            if (!ni.isInteger()){
                helper(ni.getList(), depth + 1, res);
            } else {
                res += ni.getInteger() *  depth;
            } 
        }
    }
}

你可能感兴趣的:(339. Nested List Weight Sum)