1. 程式人生 > >Leetcode 364: Nested List Weight Sum II

Leetcode 364: Nested List Weight Sum II

lists des and leet tin from tps pro -s

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.

Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.

Example 1:
Given the list [[1,1],2,[1,1]], return 8. (four 1‘s at depth 1, one 2 at depth 2)

Example 2:
Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)

 1 /**
 2  * // This is the interface that allows for creating nested lists.
3 * // You should not implement it, or speculate about its implementation 4 * interface NestedInteger { 5 * 6 * // Constructor initializes an empty nested list. 7 * public NestedInteger(); 8 * 9 * // Constructor initializes a single integer. 10 * public NestedInteger(int value);
11 * 12 * // @return true if this NestedInteger holds a single integer, rather than a nested list. 13 * bool IsInteger(); 14 * 15 * // @return the single integer that this NestedInteger holds, if it holds a single integer 16 * // Return null if this NestedInteger holds a nested list 17 * int GetInteger(); 18 * 19 * // Set this NestedInteger to hold a single integer. 20 * public void SetInteger(int value); 21 * 22 * // Set this NestedInteger to hold a nested list and adds a nested integer to it. 23 * public void Add(NestedInteger ni); 24 * 25 * // @return the nested list that this NestedInteger holds, if it holds a nested list 26 * // Return null if this NestedInteger holds a single integer 27 * IList<NestedInteger> GetList(); 28 * } 29 */ 30 public class Solution { 31 public int DepthSumInverse(IList<NestedInteger> nestedList) { 32 if (nestedList == null || nestedList.Count == 0) return 0; 33 34 var list = new List<int>(); 35 var queue = new Queue<NestedInteger>(); 36 37 foreach (var n in nestedList) 38 { 39 queue.Enqueue(n); 40 } 41 42 int cur = 0, count = queue.Count, result = 0; 43 44 while (queue.Count > 0) 45 { 46 for (int i = 0; i < count; i++) 47 { 48 var n = queue.Dequeue(); 49 if (n.IsInteger()) 50 { 51 cur += n.GetInteger(); 52 } 53 else 54 { 55 foreach (var l in n.GetList()) 56 { 57 queue.Enqueue(l); 58 } 59 } 60 } 61 62 list.Add(cur); 63 cur = 0; 64 count = queue.Count; 65 } 66 67 for (int i = list.Count - 1; i >= 0; i--) 68 { 69 result += list[i] * (list.Count - i); 70 } 71 72 return result; 73 } 74 }

Leetcode 364: Nested List Weight Sum II