三刷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);
            }
        }                                
    }
}

看看提交記錄,最近狀態是比較好,進步也是實實在在的.


image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容