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

[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:

  1. 首先明确什么信息需要提取并保存的,这题就是保存每一层数的和;
  2. 把相同层次的数字先相加,保存在数组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的特点:先把嵌套数据每一层求和,等求和完成后,便得到每一层的权重,再求加权和。问题就是,把求和、求权重分割开来。是否能够逐渐求出加权和?例如:[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
  2. 参考:https://discuss.leetcode.com/topic/49041/no-depth-variable-no-multiplication, 不用乘法,累加得到。
  3. 学习如何在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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值