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
- Nested List Weight Sum II
- Nested List Weight Sum II
- LeetCode 364. Nested List Weight Sum II
- Leetcode 364 Nested List Weight Sum II
- 364. Nested List Weight Sum II
- 364. Nested List Weight Sum II
- Nested List Weight Sum
- Nested List Weight Sum
- Leetcode 339. Nested List Weight Sum & 364. Nested List Weight Sum II
- [leetcode] 364. Nested List Weight Sum II 解题报告
- Medium 364题 Nested List Weight Sum II
- [Leetcode] 364. Nested List Weight Sum II 解题报告
- Leetcode Nested List Weight Sum
- Leetcode: Nested List Weight Sum
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- Leetcode Everyday: 339. Nested List Weight Sum
- 51nod oj 1088 1089 最长回文子串 【Manacher算法】
- 对overflow与zoom”清除浮动”的一些认识 张鑫旭博客笔记
- 周记(From 2016/08/09 to 2016/08/16)
- 机器学习(周志华) 参考答案 第七章 贝叶斯分类器 7.6
- Maven archetype 工程的创建
- Nested List Weight Sum II
- EasyUI 使用备忘
- 购物管理系统 分享一下下
- Maven 修改本地存储库位置
- 机器学习(周志华) 参考答案 第七章 贝叶斯分类器
- 蛇形打印矩阵
- Android实现一个APP只能在一部手机上使用
- JavaMail邮件的发送
- Android-自定义preference和PreferenceFragment实例详解