三刷339. Nested List Weight Sum

Easy
是L家tag题,又是DFS就比较想刷,然后算是bug free吧

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {
    int sum = 0;
    public int depthSum(List<NestedInteger> nestedList) {
        if (nestedList == null || nestedList.size() == 0){
            return 0;
        }
        dfsHelper(nestedList, 1);
        return sum;
    }
    
    private void dfsHelper(List<NestedInteger> niList, int level){
        for (NestedInteger ni : niList){
            if (ni.isInteger()){
                sum += ni.getInteger() * level;
            } else {
                dfsHelper(ni.getList(), level + 1);
            }
        }                                
    }
}

看看提交记录,最近状态是比较好,进步也是实实在在的.

《三刷339. Nested List Weight Sum》 image.png

    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/7116612c5cb1
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞