三刷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 getList();
 * }
 */
public class Solution {
    int sum = 0;
    public int depthSum(List nestedList) {
        if (nestedList == null || nestedList.size() == 0){
            return 0;
        }
        dfsHelper(nestedList, 1);
        return sum;
    }
    
    private void dfsHelper(List 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_第1张图片
image.png

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