LeetCode 339 Nested List Weight Sum

LeetCode 339 Nested List Weight Sum

==========================

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:Given the list [[1,1],2,[1,1]]
, return 10. (four 1's at depth 2, one 2 at depth 1)
Example 2:Given the list [1,[4,[6]]]
, return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 42 + 63 = 27)

题目给出了一个不太常见的数据结构,并且给出了对应interface的实现。看到嵌套深度作为权重,第一反应是dfs。

一般dfs如果需要求深度

  1. 将深度depth作为返回值,常见于min,max tree depth这类问题中。
  2. 将深度作为dfs函数的形式参数,随着dfs的深入逐渐增加。

本题需要用到第二种用法。需要注意求和的递归分解。每一次都可以得到一个List<NestedInteger>或者NestedInteger。若为NestedInteger则直接返回该integer的值乘以depth;若得到List<NestedInteger>,则遍历list继续向下递归求解每一个NestedInteger的值。

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *
 *     // @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();
 *
 *     // @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 depthSum(List<NestedInteger> nestedList) {
        if (nestedList == null) return 0;
        else {
            int sum = 0;
            for (NestedInteger x : nestedList) {
                sum += dfs(x,1);       
            }
            return sum;
        }
    }
    
    public int dfs(NestedInteger nestedInt, int depth) {
        if (nestedInt.isInteger()) {
            return nestedInt.getInteger() * depth;
        } else {
            int sum = 0;
            for (NestedInteger x : nestedInt.getList()) {
                sum += dfs(x,depth+1);
            }
            return sum;
        }
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,418评论 0 23
  • 我从小脾气就不好,但读书成绩好,重点大学本科毕业之后,参加工作工资从两千涨到了两万,加上年终奖的话,一年至少得有3...
    90后空巢老人阅读 1,391评论 0 1
  • 最近在日更的时候,我的状态与之前的有非常显著的不同。在使用价值上,最近的日更越来越趋向于低水平。 我知道自己的问题...
    玉成阅读 2,312评论 0 0
  • CSS3 动画结束时是有触发事件的,这个之前竟然不了解。。除了JS动画如果做纯css3动画的时候使用 delay ...
    我是大师兄啊阅读 5,344评论 0 0