Nested List Weight Sum
Question (LC.339)
Given a nested list of integers, return the weighted sum.
Example
I: [[1,1],2,[1,1]]
O: 2*2 + 2 + 2*2 = 10
I: [1,[4,[6]]]
O: 1 + 4 * 2 + 6 * 3 = 1 + 8 + 18 = 27What about empty list? 0
DFS Approach
1. define subproblem
dfsSum will sum up all possible sum for the current level
2. recursive calls
currentSum += sumDfs()
3. stop condition
end of the list returnCode
BFS Approach
What about BFS? It's easy once we see the nested list as tree. When doing the level order traversal, check if it is list, if so put it back in queue.
Code
Follow Up (LC.364)
Now the weight is defined bottom up. The leaf level has weight 1 and so on.
Example
DFS Approach
The most obviously approach is doing a two-pass DFS. The first pass is to find the depth. Then the second pass computes the inverse sum with knowledge of the depth.
BFS Approach
Compound sum approach. Layer up as we go.
Last updated