c++, 3ms, DFS one pass


  • 0
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        if (nestedList.empty()) return 0;
        int res=0,total=0,depth=0;
        dfs(res,total,depth,1,nestedList);
        return total*(depth+1)-res;
    }
    void dfs(int& res, int& total, int& depth, int level, vector<NestedInteger>& nestedList){
        for (auto &x:nestedList){
            if (x.isInteger()){
                res+=x.getInteger()*level;
                total+=x.getInteger();
                depth = max(depth,level);
            }else{
                auto &y = x.getList();
                dfs(res,total,depth,level+1,y);
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.