leetcode 339.Nested List Weight Sum
来源:互联网 发布:sql修改列默认值 编辑:程序博客网 时间:2024/05/16 18:14
Nested List Weight Sum
https://leetcode.com/problems/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 + 4*2 + 6*3 = 27)
题目说是吧有这么个list, 问按照list的深度加权,来求出所有元素的和是多少。
比较简单点的解法可以直接count 方括号的深度,开始一个方括号'['就加一,结束一个']'就减一。
但是题目很蛋疼的说,我们这些元素全都是obj,你得调用这些obj得方法。
简单得递归一下就ok了
值得注意的是,一开始的函数没有权重的输入参数,而且给的输入是一个list。
于是不得不重写一个可以递归的函数了。
python代码和要求如下:
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class Solution(object):
def depthSum(self, nestedList):
"""
:type nestedList: List[NestedInteger]
:rtype: int
"""
result = 0
if not nestedList:
return result
for i in nestedList:
result+=self.weightSum(i,1)
# already a list of nested integers
return result
def weightSum(self, nestedList, level):
result = 0
if not nestedList:
return result
if nestedList.isInteger():
return level*nestedList.getInteger()
else:
nestedList_new = nestedList.getList()
for i in nestedList_new:
result+=self.weightSum(i,level+1)
return result
- Leetcode Everyday: 339. Nested List Weight Sum
- LeetCode 339. Nested List Weight Sum
- leetcode 339.Nested List Weight Sum
- Leetcode Nested List Weight Sum
- Leetcode: Nested List Weight Sum
- Leetcode 339. Nested List Weight Sum & 364. Nested List Weight Sum II
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- [leetcode] 339. Nested List Weight Sum 解题报告
- LeetCode 339. Nested List Weight Sum(加权和)
- [Leetcode] 339. Nested List Weight Sum 解题报告
- LeetCode 364. Nested List Weight Sum II
- Leetcode 339 Nested List Weight Sum
- Leetcode 364 Nested List Weight Sum II
- Leetcode-Algorithms Nested List Weight Sum
- Nested List Weight Sum
- Nested List Weight Sum
- 网络爬虫项目开发日志(一):关于爬虫项目所涉及的领域知识
- Design Pattern - Structural Patterns - Facade Pattern
- COCI2009 着色
- C# 关键字(Static/Const/Readonly)
- SpringMVC中使用Interceptor拦截器
- leetcode 339.Nested List Weight Sum
- Restore Volume 操作 - 每天5分钟玩转 OpenStack(60)
- 数据库入门
- Spring系列之简单的应用实例
- Cocos2d-x 图像渲染和动画——粒子系统
- sessionstorage,localstorage和cookie
- 小鸟云服务器linux版本的登陆
- Java中字节流和异常处理
- RxSwift - API