364. Nested List Weight Sum II - cocoder39/coco39_LC GitHub Wiki
364. Nested List Weight Sum II
The code below can not pass test case like [[-1],[[-1]]]
class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
int res = 0;
helper(res, nestedList);
return res;
}
private:
int helper(int& res, vector<NestedInteger>& nestedList) {
int height = 0;
int sum_int = 0;
for (auto &nl : nestedList) {
if (nl.isInteger()) {
sum_int += nl.getInteger();
height = max(height, 1);
}
else {
height = max(height, helper(res, nl.getList()) + 1);
}
}
res += sum_int * height;
return height;
}
};
two NestedInteger
s in the same depth may be separated by NestedInteger
in deeper depth, hard to determine the depth without pass depth
as an argument
class Solution {
public:
int depthSumInverse(vector<NestedInteger>& nestedList) {
vector<int> sum;
helper(sum, nestedList, 0);
int res = 0;
for (int i = 0; i < sum.size(); i++) {
res += sum[i] * (sum.size() - i);
}
return res;
}
private:
void helper(vector<int>& sum, vector<NestedInteger>& nestedList, int depth) {
if (sum.size() == depth) {
sum.push_back(0);
}
for (auto &ni : nestedList) {
if (ni.isInteger()) {
sum[depth] += ni.getInteger();
}
else {
helper(sum, ni.getList(), depth + 1);
}
}
}
};