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 [leetcode]339. Nested List Weight Sum嵌套列表加权和 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:

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; 1*3 + 4*2 + 6*1 = 17.

思路

跑的最快的方法是 DFS

1. We can observe that

1x + 2y + 3z  = (x+y+z) * (3+1)    -   (3x+2y+1z)

^ levelSum  ^maxDepth   ^ Nested List Weight Sum I problem

2. Use DFS recursion, converting this problem to Nested List Weight Sum I,  updating levelSum and maxPath at the same time when using DFS

代码

 class Solution {
int levelSum = 0;
int maxDepth = 1; public int depthSumInverse(List<NestedInteger> nestedList) {
int depthSum = dfs(nestedList, 1);
return levelSum * (maxDepth + 1) - depthSum;
} private int dfs(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for (NestedInteger n : nestedList) {
if (n.isInteger()) {
// same as Nested List Weight Sum I
sum += n.getInteger() * depth;
// at the same time, use DFS to update levelSum and maxDepth
maxDepth = Math.max(depth, maxDepth);
levelSum += n.getInteger();
} else {
// same as Nested List Weight Sum I
sum += dfs(n.getList(), depth + 1);
}
}
return sum;
}
}

思路

最容易想到的方法 DFS

1. use helper function to get maxDepth

2. same as Nested List Weight Sum I, use dfs function to get result. Only concerning that do substraction instead of addition when entering next new level

 class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
// corner case
if(nestedList == null || nestedList.size() == 0) return 0;
int depth = helper(nestedList);
int sum = dfs(nestedList, depth);
return sum;
}
// helper recursion function to get the maxDepth
public int helper(List<NestedInteger> nestedList) {
int depth = 0;
for (NestedInteger n : nestedList) {
if(n.isInteger()) {
depth = Math.max(depth, 1);
}
else {
depth = Math.max(depth, helper(n.getList()) + 1);
}
}
return depth;
} // same as Nested List Weight Sum I
public int dfs(List<NestedInteger> nestedList, int depth) {
int result = 0;
for (NestedInteger n : nestedList) {
if (n.isInteger()) {
result += n.getInteger() * depth;
} else {
result += dfs(n.getList(), depth - 1);
}
}
return result;
}
}

思路

BFS(level order traversal)

if we want to get 3x + 2y + 1z, we can use preSum tech like that

levelSum    x

preSum      x

result        x

=======================

levelSum    x     y

preSum      x    x+y

result         x    x + x + y

=======================

levelSum    x     y             z

preSum      x    x+y           x+y+z

result         x    x + x + y    x + x + y + x + y + z

代码

 class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
// corner case
if(nestedList == null || nestedList.size() == 0) return 0;
// initialize
int preSum = 0;
int result = 0;
// put each item of list into the queue
Queue<NestedInteger> queue = new LinkedList<>(nestedList);
while(!queue.isEmpty()){
//depends on different depth, queue size is changeable
int size = queue.size();
int levelSum = 0;
for(int i = 0; i < size; i++){
NestedInteger n = queue.poll();
if(n.isInteger()){
levelSum += n.getInteger();
}
else{
// depends on different depth, queue size is changeable
queue.addAll(n.getList());
}
}
preSum += levelSum;
result += preSum;
}
return result;
}
}

[leetcode]364. Nested List Weight Sum II嵌套列表加权和II的更多相关文章

  1. 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. ...

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

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  3. LeetCode 364. Nested List Weight Sum II

    原题链接在这里:https://leetcode.com/problems/nested-list-weight-sum-ii/description/ 题目: Given a nested list ...

  4. [LeetCode] 364. Nested List Weight Sum II_Medium tag:DFS

    Given a nested list of integers, return the sum of all integers in the list weighted by their depth. ...

  5. [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. ...

  6. LeetCode 339. Nested List Weight Sum

    原题链接在这里:https://leetcode.com/problems/nested-list-weight-sum/ 题目: Given a nested list of integers, r ...

  7. 【LeetCode】364. Nested List Weight Sum II 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  8. 364. Nested List Weight Sum II 大小反向的括号加权求和

    [抄题]: Given a nested list of integers, return the sum of all integers in the list weighted by their ...

  9. 364. Nested List Weight Sum II

    这个题做了一个多小时,好傻逼. 显而易见计算的话必须知道当前层是第几层,因为要乘权重,想要知道是第几层又必须知道最高是几层.. 用了好久是因为想ONE PASS,尝试过遍历的时候构建STACK,通过和 ...

随机推荐

  1. 什么是pytorch(2Autograd:自动求导)(翻译)

    Autograd: 自动求导 pyTorch里神经网络能够训练就是靠autograd包.我们来看下这个包,然后我们使用它来训练我们的第一个神经网络. autograd 包提供了对张量的所有运算自动求导 ...

  2. expect脚本实现ssh自动登录

    1:简单的实现ssh登录 #!/usr/bin/expect set ip "10.0.0.142" set user "root" set password ...

  3. 日期date出参入参和timestamp转化

    日期传到form页面,注意MM要大写 由于Date在MySQL没有默认值,没有设置的时候,会自动变成0000-00-00,影响渲染到Java类中,所以需要在程序中设置默认值 date转timestam ...

  4. C# 数据库

    连接: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...

  5. AIUI开放平台:多轮对话返回前几轮语槽数据

    编写云函数: AIUI.create("v2", function(aiui, err){ // 获取 response response = aiui.getResponse() ...

  6. xshell 显示中文

    xshell 可能无法正常显示中文,即使选择了utf-8编码也不生效. 1:输入:echo $LANG 显示:en_US.UTF-8 2.输入:export LANG=zh_CN.UTF-8 3. 输 ...

  7. Docker Images for MySQL Group Replication 5.7.14

    In this post, I will point you to Docker images for MySQL Group Replication testing. There is a new ...

  8. Dubbo源码阅读顺序

    转载: https://blog.csdn.net/heroqiang/article/details/85340958 Dubbo源码解析之配置解析篇,主要内容是<dubbo:service/ ...

  9. 【学习】通用函数:快速的元素级数组函数【Numpy】

    通用函数(即ufunc)是一种对ndarray中的数据执行元素级运算的函数.可以将其看做简单函数(接受一个或多个标量值,并产生一个或多个标量值)的矢量化包装器. sqrt 和 exp为一元(unary ...

  10. python——数字问题之_ 变量

    在交互模式中,最后被输出的表达式结果被赋值给变量 _ ._ 变量应被用户视为只读变量 >>> a=12/2.3 >>> b=1.2 >>> a*b ...