您的位置:首页 > 其它

LeetCode 364. Nested List Weight Sum II 嵌套链表权重和之二

2017-01-04 10:27 369 查看
[LeetCode] Nested List Weight Sum II 嵌套链表权重和之二

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.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1: Given the list [[1,1],2,[1,1]], return 8. (four 1’s at

depth 1, one 2 at depth 2)

Example 2: Given the list [1,[4,[6]]], return 17. (one 1 at depth 3,

one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)

思路1:

首先明确什么信息需要提取并保存的,这题就是保存每一层数的和;

把相同层次的数字先相加,保存在数组sum中,然后根据数组的size确定第i层的depth=size-i,然后depth*sum[i]得到第i层的权重,最后累加所有层的权重。

int depthSum(vector<NestedInteger>& nestedList) {
//
vector<int> sum;
helper(ni,0,sum);
int res=0;
for(int i=0;i<sum.size();i++){
res+=sum[i]*(sum.size()-i);
}
return res;
}

void helper(vector<NestedInteger>& ni,int depth, vector<int> sum){
if(sum.size()<=depth) sum.resize(depth+1);
for(auto&k:ni){
if(k.isInteger()){
sum[depth]+=k;
}else{
helper(ni,depth+1,sum);
}
}
}


思路2:

观察思路1的特点:先把嵌套数据每一层求和,等求和完成后,便得到每一层的权重,再求加权和。问题就是,把求和、求权重分割开来。是否能够逐渐求出加权和?例如:[1,[4,[6]]]: 碰到1时,partialSum=1,total=1;碰到4时,partialSum=1+4,total=1+(1+4);碰到6时,partialSum=1+4+6,total=1+(1+4)+(1+4+6)。也就是1×3+4×2+6×1

参考:https://discuss.leetcode.com/topic/49041/no-depth-variable-no-multiplication, 不用乘法,累加得到。

学习如何在vector 中插入一个新的vector:用vector.insert()

int depthSum(vector<NestedInteger>& nestedList) {
//

int total=0,partial=0;
vector<NestedInteger> nextLevel;
while(!nestedList.empty()){
for(auto&k:nestedList){
if(k.isInteger()){
partial+=k;
}else{
nextLevel.insert(nextLevel.end(),k.begin(),k.end());
}
}
total+=partial;
nestedList=nextLevel;
}
return total;
}

void helper(vector<NestedInteger>& ni,int depth, vector<int> sum){
if(sum.size()<=depth) sum.resize(depth+1);
for(auto&k:ni){
if(k.isInteger()){
sum[depth]+=k;
}else{
helper(ni,depth+1,sum);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 链表