Example 1:
Input: [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1’s at depth 1, one 2 at depth 2.
Example 2:
Input: [1,[4,[6]]]
Output: 17
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 13 + 42 + 6*1 = 17.
先找到depth,再像之前做法一样
class Solution {
int count=0;
public int depthSumInverse(List<NestedInteger> nestedList) {
finddepth(nestedList,0);
return find(nestedList,count);
}
public void finddepth(List<NestedInteger> list,int depth){
for (NestedInteger n : list) {
if(n.isInteger()) {
if(depth+1>count) count=depth+1;
}
else{
finddepth(n.getList(),depth+1);
}
}
}
public int find(List<NestedInteger> list,int weight){
int sum=0;
for (NestedInteger n : list) {
if(n.isInteger()) {
sum+=n.getInteger()*weight;
}
else{
sum+=find(n.getList(),weight-1);
}
}
return sum;
}
}
本文介绍了一种深度加权求和算法,通过计算列表中嵌套整数的深度和权重来得出总和。提供了两个示例,详细解释了算法的工作原理。首先确定最大深度,然后从最大深度开始计算每个整数的加权值。
5592

被折叠的 条评论
为什么被折叠?



