Leetcode - Nested List Weight Sum II

My code:

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *     // Constructor initializes an empty nested list.
 *     public NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     public NestedInteger(int value);
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // Set this NestedInteger to hold a single integer.
 *     public void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     public void add(NestedInteger ni);
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
public class Solution {
    public int depthSumInverse(List<NestedInteger> nestedList) {
        int unweighted = 0;
        int weighted = 0;
        List<NestedInteger> next = new ArrayList<NestedInteger>();
        while (nestedList.size() != 0) {
            for (NestedInteger temp : nestedList) {
                if (temp.isInteger()) {
                    unweighted += temp.getInteger();
                }
                else {
                    next.addAll(temp.getList());
                }
            }
            weighted += unweighted;
            nestedList = next;
            next = new ArrayList<NestedInteger>();
        }
        
        return weighted;
    }
}

这道题目并没有做出来。。。
觉得会很复杂。看答案,没想到思路如此简洁简单。
每次总是这样,自己觉得很复杂的问题,他们用很简洁的思路就做了出来,那些我考虑的恶心的东西,他们根本不考虑。

reference:
https://discuss.leetcode.com/topic/49041/no-depth-variable-no-multiplication

关键在于,
即使一个数在他的那一枝是叶子,不代表他可以 乘以 1

因为如果还有更深的结点,那他的层数就大于 1

所以可以用累加的方式。

比如最开始一层是 5,我们无法确定它的深度,
那就每一层都加上他。这样就一定能保证它的深度正确。

Anyway, Good luck, Richardo! — 09/10/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/8c1a9283c452#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞