Java Solution using DFS


  • 0
    public int depthSumInverse(List<NestedInteger> nestedList) {
        List<Integer> list = new ArrayList<>();
        for(NestedInteger target: nestedList) {
            depthSumInverseHelper(list, 1, target);
        }
        System.out.println(list);
        int res = 0;
        for(int i=0; i<list.size(); i++) {
            res += list.get(i) * (list.size()-i);
        }
        return res;
    }
    
    public void depthSumInverseHelper(List<Integer> list, int level, NestedInteger target) {
        if(target.isInteger()) {
            for(int i=list.size(); i<level; i++) {
                list.add(0);
            }
            list.set(level-1, list.get(level-1) + target.getInteger());
        } else {
            for(NestedInteger tmp: target.getList()) {
                depthSumInverseHelper(list, level+1, tmp);
            }
        }
    }

Log in to reply
 

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