Skip to content

Commit 5afe80e

Browse files
authored
Update and rename 339. Nested List Weight Sum.md to 339._Nested_List_Weight_Sum.md
1 parent 2284e80 commit 5afe80e

File tree

2 files changed

+54
-58
lines changed

2 files changed

+54
-58
lines changed

docs/Leetcode_Solutions/Python/339. Nested List Weight Sum.md

Lines changed: 0 additions & 58 deletions
This file was deleted.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# 339. Nested List Weight Sum
2+
3+
**<font color=red>难度: Easy</font>**
4+
5+
## 刷题内容
6+
7+
> 原题连接
8+
9+
* https://leetcode.com/problems/nested-list-weight-sum/description/
10+
11+
> 内容描述
12+
13+
```
14+
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
15+
16+
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
17+
18+
Example 1:
19+
20+
Input: [[1,1],2,[1,1]]
21+
Output: 10
22+
Explanation: Four 1's at depth 2, one 2 at depth 1.
23+
Example 2:
24+
25+
Input: [1,[4,[6]]]
26+
Output: 27
27+
Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27.
28+
```
29+
30+
## 解题方案
31+
32+
> 思路 1
33+
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******
34+
35+
很简单的递归
36+
37+
假设nestedList铺平开来,里面一共有N个NestedInteger的话,时间复杂度就是O(N)
38+
```python
39+
class Solution:
40+
def depthSum(self, nestedList):
41+
"""
42+
:type nestedList: List[NestedInteger]
43+
:rtype: int
44+
"""
45+
def helper(nestedList, depth):
46+
res = 0
47+
for nested in nestedList:
48+
if nested.isInteger():
49+
res += depth * nested.getInteger()
50+
else:
51+
res += helper(nested.getList(), depth+1)
52+
return res
53+
return helper(nestedList, 1)
54+
```

0 commit comments

Comments
 (0)