[LeetCode] 364. Nested List Weight Sum II

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists.

The depth of an integer is the number of lists that it is inside of. For example, the nested list [1,[2,2],[[3],2],1] has each integer's value set to its depth. Let maxDepth be the maximum depth of any integer.

The weight of an integer is maxDepth - (the depth of the integer) + 1.

Return the sum of each integer in nestedList multiplied by its weight.

Example 1:

Input: nestedList = [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1's with a weight of 1, one 2 with a weight of 2.
1*1 + 1*1 + 2*2 + 1*1 + 1*1 = 8

Example 2:

Input: nestedList = [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

Constraints:

  • 1 <= nestedList.length <= 50
  • The values of the integers in the nested list is in the range [-100, 100].
  • The maximum depth of any integer is less than or equal to 50.

加权嵌套序列和 II。

题意跟版本一339题很像,唯一不同的是计算权重和的方式。在339题中,最外层的数字的权重越小,越内层的数字的权重越大;这道题是最外层的权重是最大的,最内层的权重是最小的。计算每一层的权重和都需要知道当前层的权重是多少,但是如何得知最外层的权重是多少呢。我这里提供一个BFS的方法。思路是遍历input,还是跟版本一一样把遍历到的NestedInteger加入queue。但是这里我们同时记录一个levelSum,也创建一个stack。当计算好当前层的和之后,将这个和入栈,这样弹出的时候,最先入栈的数字则带有最高的权重,跟题意符合。DFS的思路之后有机会我再补充。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int depthSumInverse(List<NestedInteger> nestedList) {
 3         // corner case
 4         if (nestedList == null) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         int res = 0;
10         Queue<NestedInteger> queue = new LinkedList<>();
11         Stack<Integer> stack = new Stack<>();
12         queue.addAll(nestedList);
13         while (!queue.isEmpty()) {
14             int size = queue.size();
15             int levelSum = 0;
16             for (int i = 0; i < size; i++) {
17                 NestedInteger cur = queue.poll();
18                 if (cur.isInteger()) {
19                     levelSum += cur.getInteger();
20                 } else {
21                     queue.addAll(cur.getList());
22                 }
23             }
24             stack.push(levelSum);
25         }
26         int depth = 1;
27         while (!stack.isEmpty()) {
28             res += depth * stack.pop();
29             depth++;
30         }
31         return res;
32     }
33 }

 

相关题目

339. Nested List Weight Sum

364. Nested List Weight Sum II

690. Employee Importance

LeetCode 题目总结

posted @ 2020-08-21 14:48  CNoodle  阅读(260)  评论(0编辑  收藏  举报