美文网首页
339-嵌套列表权重和

339-嵌套列表权重和

作者: 饮酒醉回忆 | 来源:发表于2019-06-19 11:18 被阅读0次

嵌套列表权重和

题目

给定一个嵌套的整数列表,请返回该列表按深度加权后所有整数的总和。

每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。

示例 1:

输入: [[1,1],2,[1,1]]
输出: 10 
解释: 因为列表中有四个深度为 2 的 1 ,和一个深度为 1 的 2。

示例 2:

输入: [1,[4,[6]]]
输出: 27 
解释: 一个深度为 1 的 1,一个深度为 2 的 4,一个深度为 3 的 6。所以,1 + 4*2 + 6*3 = 
27。

思路

首先是对题目给出的接口理解,和判断文件,文件夹是一个意思.使用递归来解决

代码

/**
 * // 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();
 * }
 */
class Solution {
    public int depthSum(List<NestedInteger> nestedList) {
        return getDepthSum(nestedList, 1);
    }
    
    private int getDepthSum(List<NestedInteger> nestedList, int curDepth){
        int sum = 0;
        for(NestedInteger ni : nestedList){
            if(ni.isInteger()){
                sum += ni.getInteger() * curDepth;
            }else {
                sum += getDepthSum(ni.getList(), curDepth+1);
            }
        }
        return sum;
    }
}

相关文章

  • 339-嵌套列表权重和

    嵌套列表权重和 题目 给定一个嵌套的整数列表,请返回该列表按深度加权后所有整数的总和。 每个元素要么是整数,要么是...

  • markdown test

    一级标题 二级标题 三级标题 嵌套列表嵌套列表嵌套列表嵌套列表嵌套列表嵌套列表 无序列表 无序列表 有序列表1 有...

  • 一 -18 python (基础)列表的镶嵌

    列表嵌套 类似while循环的嵌套,列表也是支持嵌套的 一个列表中的元素又是一个列表,那么这就是列表的嵌套叫做二维...

  • Python基础_04:列表(2019-1-13)

    列表 列表嵌套

  • python(7):字典(2)

    1.嵌套 将一系列字典存贮再列表中,或将列表作为值存贮在字典中,称为嵌套。可以在列表中嵌套字典,字典中嵌套列表,字...

  • HTML第一阶段四五天

    1、列表 ul 和ol中尽量不要嵌套其他的标签 但是li 标签里面可以嵌套其他标签 1.1、无序列表(unorde...

  • Markdown 语法

    标题 区块引用 Blockquotes 区块引用可以嵌套 列表 Markdown 支持有序列表和无序列表。无序列表...

  • HTML列表

    HTML支持有序、无序和定义列表无序列表: 有序列表: 嵌套列表: 自定义列表: HTML 列表标签 定义有序列表...

  • 循环嵌套与算法

    本节大纲 循环嵌套 列表生成式 排序算法 循环嵌套 列表生成式 排序算法

  • 用HTML来写列表

    考虑用html如何实现以下列表: 要实现的是有序列表和无序列表以及嵌套列表的结合 有序列表: 定义和用法: ...

网友评论

      本文标题:339-嵌套列表权重和

      本文链接:https://www.haomeiwen.com/subject/ctphqctx.html