LeetCode 339 Nested List Weight Sum
==========================
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:Given the list [[1,1],2,[1,1]]
, return 10. (four 1's at depth 2, one 2 at depth 1)
Example 2:Given the list [1,[4,[6]]]
, return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27)
题目给出了一个不太常见的数据结构,并且给出了对应interface的实现。看到嵌套深度作为权重,第一反应是dfs。
一般dfs如果需要求深度
- 将深度depth作为返回值,常见于min,max tree depth这类问题中。
- 将深度作为dfs函数的形式参数,随着dfs的深入逐渐增加。
本题需要用到第二种用法。需要注意求和的递归分解。每一次都可以得到一个List<NestedInteger>或者NestedInteger。若为NestedInteger则直接返回该integer的值乘以depth;若得到List<NestedInteger>,则遍历list继续向下递归求解每一个NestedInteger的值。
/**
* // 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 depthSum(List<NestedInteger> nestedList) {
if (nestedList == null) return 0;
else {
int sum = 0;
for (NestedInteger x : nestedList) {
sum += dfs(x,1);
}
return sum;
}
}
public int dfs(NestedInteger nestedInt, int depth) {
if (nestedInt.isInteger()) {
return nestedInt.getInteger() * depth;
} else {
int sum = 0;
for (NestedInteger x : nestedInt.getList()) {
sum += dfs(x,depth+1);
}
return sum;
}
}
}