My one pass solution


  • 0
    T

    public class Solution {

    int max = 1;
    int result = 0;
    int sum = 0;
    
    public int DepthSumInverse(IList<NestedInteger> nestedList) {
        dfs(nestedList,1);
        return result;
    }
    
    private void dfs(IList<NestedInteger> nestedList,int index){
        foreach(var item in nestedList){
            if(item.IsInteger()){
                if(index == max)
                    result += item.GetInteger();
                else if(index < max)
                    result += item.GetInteger()*(max-index+1);
                else{
                    result += sum * (index-max) + item.GetInteger();
                    max = index;
                }
                sum += item.GetInteger();
            }else{
                if(item.GetList().Any()){
                    dfs(item.GetList(),index+1);
                }
            }
        }
    }
    

    }


Log in to reply
 

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