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)
Solution1:BFS
Time Complexity: O(N) Space Complexity: O(N)
Solution2:DFS(recursive)
Time Complexity: O(N) Space Complexity: O(N)
Solution3:DFS(stack)
Time Complexity: O(N) Space Complexity: O(N)
Solution1 Code:
public class Solution {
public int depthSum(List<NestedInteger> nestedList) {
if(nestedList == null){
return 0;
}
int sum = 0;
int level = 1;
Queue<NestedInteger> queue = new LinkedList<NestedInteger>(nestedList);
while(queue.size() > 0){
int size = queue.size();
for(int i = 0; i < size; i++){
NestedInteger ni = queue.poll();
if(ni.isInteger()){
sum += ni.getInteger() * level;
} else {
queue.addAll(ni.getList());
}
}
level++;
}
return sum;
}
}
Solution2 Code:
class Solution {
public int depthSum(List<NestedInteger> nestedList) {
return depthSum(nestedList, 1);
}
public int depthSum(List<NestedInteger> nestedList, int level) {
int result = 0;
for(NestedInteger ni : nestedList) {
if (ni.isInteger()) {
result += (level * ni.getInteger());
}else {
result += depthSum(ni.getList(), level + 1);
}
}
return result;
}
}
Solution3 Code:
public class Solution {
public int depthSum(List<NestedInteger> nestedList) {
int res = 0;
Stack<Iterator<NestedInteger>> stk = new Stack<>();
stk.push (nestedList.iterator());
while (!stk.isEmpty()) {
Iterator<NestedInteger> itr = stk.peek();
while (itr.hasNext()) {
NestedInteger n = itr.next();
if (n.isInteger()) res += n.getInteger() * stk.size ();
else {
stk.push(n.getList().iterator());
break;
}
}
if (!stk.peek().hasNext()) stk.pop();
}
return res;
}
}