leetcode339. 嵌套列表权重和

举报
兔老大 发表于 2021/04/24 00:55:36 2021/04/24
【摘要】 给定一个嵌套的整数列表,请返回该列表按深度加权后所有整数的总和。 每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。 示例 1: 输入: [[1,1],2,[1,1]] 输出: 10  解释: 因为列表中有四个深度为 2 的 1 ,和一个深度为 1 的 2。 示例 2: 输入: [1,[4,[6]]] 输出: 27  解释: 一个深度为...

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

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

示例 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。

思路:其实时间主要浪费在读题上了,不知道这个NestedInteger怎么用,是个啥东西。

就是最简单的搜索。


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

 

文章来源: fantianzuo.blog.csdn.net,作者:兔老大RabbitMQ,版权归原作者所有,如需转载,请联系作者。

原文链接:fantianzuo.blog.csdn.net/article/details/104103497

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。