题目描述:
给一个嵌套整数序列,请你返回每个数字在序列中的加权和,它们的权重由它们的深度决定。
序列中的每一个元素要么是一个整数,要么是一个序列(这个序列中的每个元素也同样是整数或序列)。
与 前一个问题 不同的是,前一题的权重按照从根到叶逐一增加,而本题的权重从叶到根逐一增加。
也就是说,在本题中,叶子的权重为1,而根拥有最大的权重。
示例 1:
输入: [[1,1],2,[1,1]]
输出: 8
解释: 四个 1 在深度为 1 的位置, 一个 2 在深度为 2 的位置。
示例 2:
输入: [1,[4,[6]]]
输出: 17
解释: 一个 1 在深度为 3 的位置, 一个 4 在深度为 2 的位置,一个 6 在深度为 1 的位置。 13 + 42 + 6*1 = 17。
方法1:
主要思路:
(1)使用广度优先,来逐渐的解开各层内容;
(2)广度优先使用队列实现,先将输入的数组压入到队列中,作为初始化的层,然后对每一层的内容进行判断;
(3)对每层的内容取出各个元素,然后对各个元素的每个元素进行判断,判断是否是单个数字,若是,则加上对应的值,若不是,则作为新的嵌套序列压入到队列中;
(4)使用变量cur_weight统计各层各个元素的元素值,由于在每层结束时,都将该值加入到结果变量res中,就相当于处于多少层高度的父节点,就会被累加几次,故相当于乘以了对应的权重;
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that