|
| 1 | +/** |
| 2 | + * Given a nested list of integers, return the sum of all integers in the list |
| 3 | + * weighted by their depth. |
| 4 | + * |
| 5 | + * Each element is either an integer, or a list -- whose elements may also be |
| 6 | + * integers or other lists. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * Input: [[1,1],2,[1,1]] |
| 10 | + * Output: 10 |
| 11 | + * Explanation: Four 1's at depth 2, one 2 at depth 1. |
| 12 | + * |
| 13 | + * Example 2: |
| 14 | + * Input: [1,[4,[6]]] |
| 15 | + * Output: 27 |
| 16 | + * Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; |
| 17 | + * 1 + 4*2 + 6*3 = 27. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * // This is the interface that allows for creating nested lists. |
| 22 | + * // You should not implement it, or speculate about its implementation |
| 23 | + * public interface NestedInteger { |
| 24 | + * // Constructor initializes an empty nested list. |
| 25 | + * public NestedInteger(); |
| 26 | + * |
| 27 | + * // Constructor initializes a single integer. |
| 28 | + * public NestedInteger(int value); |
| 29 | + * |
| 30 | + * // @return true if this NestedInteger holds a single integer, rather than a nested list. |
| 31 | + * public boolean isInteger(); |
| 32 | + * |
| 33 | + * // @return the single integer that this NestedInteger holds, if it holds a single integer |
| 34 | + * // Return null if this NestedInteger holds a nested list |
| 35 | + * public Integer getInteger(); |
| 36 | + * |
| 37 | + * // Set this NestedInteger to hold a single integer. |
| 38 | + * public void setInteger(int value); |
| 39 | + * |
| 40 | + * // Set this NestedInteger to hold a nested list and adds a nested integer to it. |
| 41 | + * public void add(NestedInteger ni); |
| 42 | + * |
| 43 | + * // @return the nested list that this NestedInteger holds, if it holds a nested list |
| 44 | + * // Return null if this NestedInteger holds a single integer |
| 45 | + * public List<NestedInteger> getList(); |
| 46 | + * } |
| 47 | + */ |
| 48 | + |
| 49 | +public class NestedListWeightSum339 { |
| 50 | + public int depthSum(List<NestedInteger> nestedList) { |
| 51 | + return depthSum(nestedList, 1); |
| 52 | + } |
| 53 | + |
| 54 | + private int depthSum(List<NestedInteger> nestedList, int level) { |
| 55 | + int res = 0; |
| 56 | + for (NestedInteger ni: nestedList) { |
| 57 | + if (ni.isInteger()) { |
| 58 | + res += ni.getInteger() * level; |
| 59 | + } else { |
| 60 | + res += depthSum(ni.getList(), level + 1); |
| 61 | + } |
| 62 | + } |
| 63 | + return res; |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments