https://leetcode.com/problems/nested-list-weight-sum-ii/description/
Topic of the title: Conversely with 339. Nested List Weight Sum , find the weighted sum of the nested array, but the weight is the inverse of the depth Come over, the weight of the deepest layer is 1.
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)
Problem-solving idea: At the beginning, I wanted to use the method of backtracking, but I had to give up. It was still the idea of 339 questions, forward recursion, record the number of each layer in the vector record, and the number of the i-th layer The sum is record[i]. Finally, traverse the record in reverse to obtain the weighted sum.
Code:
class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
vector<int> record; //记录表
for (auto nl : nestedList) {
dfs(nl, 0, record);
}
int sum = 0;
//反向遍历求加权
for (int i = record.size()-1, level = 1; i >= 0; i--, level++) {
sum += level * record[i];
}
return sum;
}
void dfs(NestedInteger &nestedList, int depth, vector<int>& record) {
if (record.size() < depth+1) record.resize(depth+1); //record按需扩张
if (nestedList.isInteger()) {
record[depth] += nestedList.getInteger(); //递归出口,记录该层数之和
} else {
for (auto nl : nestedList.getList()) {
dfs(nl, depth+1, record);
}
}
}
};