Nested List Weight Sum II

来源:互联网 发布:淘宝营业执照代办 编辑:程序博客网 时间:2024/04/28 11:15

学习了一种,先算最大的深度,再计算的思路。

/** * // 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 {    public int depthSumInverse(List<NestedInteger> nestedList) {        int maxDepth = 1;        if (nestedList == null || nestedList.size() == 0) {            return 0;        }        maxDepth = maxDepth(nestedList, maxDepth);        int res = sum(nestedList, maxDepth);        return res;    }        private int sum(List<NestedInteger> nestedList, int depth) {        int sum = 0;        for (NestedInteger nestedInteger: nestedList) {            if (nestedInteger.isInteger()) {                sum = sum + nestedInteger.getInteger() * depth;            } else {                sum = sum + sum(nestedInteger.getList(), depth - 1);            }        }        return sum;    }        private int maxDepth(List<NestedInteger> nestedList, int depth) {        int max = depth;        for (NestedInteger nestedInteger: nestedList) {            if (!nestedInteger.isInteger()) {                max = Math.max(max, maxDepth(nestedInteger.getList(), depth + 1));            }        }        return max;    }}


0 0
原创粉丝点击