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. Centos7安装mysql5.6.29shell脚本

    创建脚本mysql.sh,直接运行sh mysql.sh #!/bin/bash if [ -d /software ] ;then cd /software else mkdir /software ...

  2. 初探JavaScript的截屏实现

    最近参与了网易炉石盒子的相关页面开发,在做卡组分享页(地址:炉石盒子卡组分享),有个需求:用户可以把这个卡组以图片的形式分享给好友.最初的的做法是使用服务器把该页面转换成图片,然后把图片地址返回给前端 ...

  3. bootstrap modal 点击头部移动

    $(".modal").each(function(){ $(this).draggable({ handle: ".modal-header" // 只能点击 ...

  4. 过滤器手动注入Service Bean方法

    @Override public void init(FilterConfig arg0) throws ServletException { ServletContext servletContex ...

  5. 使用Go编写WebAssembly

    I. Install go 1. down https://golang.org/dl/ go1.12.3.windows-amd64.zip 2. set path (1) GOROOTvar na ...

  6. 支持flash in Chrome 2017

    在设置页面: chrome://settings/content 修改Flash插件的使用方式为:Allow sites to run Flash 来源: https://helpx.adobe.co ...

  7. redis排序

    1.sort 排序最常见的是sort命令,可以对列表或者有序集合排序,最简单的排序方式如下: > lpush list (integer) > lpush list (integer) & ...

  8. 第二章 Java内存区域与内存溢出异常

    运行时数据区域: 程序计数器(Program Counter Register):当前线程执行码行号指示器,属于线程私有内存.字节码解释器工作时就是通过调整这个计数器的值来选取下一条需要执行字节码指令 ...

  9. Python模拟登陆TAPD

    因为在wiki中未找到需要的数据,查询也很迷,打算用python登录tapd抓取所需项目下的wiki数据,方便查找. 2018-9-30 19:12:44 几步走 模拟登录tapd 抓取wiki页左侧 ...

  10. 解决spring-security session超时 Ajax 请求没有重定向的问题

    开始时, 代码是这样的: $.ajax({ type : "POST", url : sSource, cache : false, dataType : "json&q ...