364. Nested List Weight Sum II

https://leetcode.com/problems/nested-list-weight-sum-ii/description/
题目大意:与339. Nested List Weight Sum反过来,求嵌套数组的加权和,只不过权重是和深度反过来,最深一层权重为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)

解题思路:一开始想用反过来回溯的方法,然并卵,最后只能放弃,还是339题的思路,正向递归,将每层的数记录在向量record中,第i层的数之和为record[i].最后再反向遍历record求加权和即可.

代码:

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); 
            }  
        }
    }
};

猜你喜欢

转载自blog.csdn.net/u012033124/article/details/79676226