FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/339_Nested_List_Weight_Sum.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
339_Nested_List_Weight_Sum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
45 lines (41 loc) · 1.57 KB
Breadcrumbs
leetcode
/
java
/
339_Nested_List_Weight_Sum.java
Copy path
File metadata and controls
45 lines (41 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
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.
For each item in list, if integer then multiply by depth and add to total, else recursively sum the list after
incrementing the depth.
Time - O(n)
Space - O(1)
*/
/**
* // 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
) {
return
helper
(
nestedList
,
1
);
}
private
int
helper
(
List
<
NestedInteger
>
nestedList
,
int
depth
) {
int
total
=
0
;
for
(
NestedInteger
n
:
nestedList
) {
if
(
n
.
isInteger
())
total
+=
n
.
getInteger
() *
depth
;
else
total
+=
helper
(
n
.
getList
(),
depth
+
1
);
}
return
total
;
}
}
Back
|
FazBrowse Home
|
New Git URL