一、Nested List Weight Sumhtml
1 class Solution { 2 public: 3 int depthSum(vector<NestedInteger>& nestedList) { 4 int res =0; 5 int level = 1; 6 for(auto p : nestedList) 7 { 8 res += levelSum(p, level); 9 } 10 return res; 11 } 12 int levelSum(NestedInteger p, int level) 13 { 14 int res =0; 15 if(p.isInterger()) return level*p.getInterger(); 16 for(auto i :p.getList()) 17 { 18 res += levelSum(i, level+1); 19 } 20 return res; 21 } 22 23 };
二、Flatten Nested List Iteratorthis
1 /** 2 * // This is the interface that allows for creating nested lists. 3 * // You should not implement it, or speculate about its implementation 4 * class NestedInteger { 5 * public: 6 * // Return true if this NestedInteger holds a single integer, rather than a nested list. 7 * bool isInteger() const; 8 * 9 * // Return the single integer that this NestedInteger holds, if it holds a single integer 10 * // The result is undefined if this NestedInteger holds a nested list 11 * int getInteger() const; 12 * 13 * // Return the nested list that this NestedInteger holds, if it holds a nested list 14 * // The result is undefined if this NestedInteger holds a single integer 15 * const vector<NestedInteger> &getList() const; 16 * }; 17 */ 18 class NestedIterator { 19 public: 20 void dfs(NestedInteger p) 21 { 22 if(p.isInteger()) 23 list.push_back(p.getInteger()); 24 for(auto i : p.getList()) 25 dfs(i); 26 } 27 NestedIterator(vector<NestedInteger> &nestedList) { 28 for(auto i : nestedList) 29 dfs(i); 30 iter = 0; 31 } 32 33 int next() { 34 return list[iter++]; 35 } 36 37 bool hasNext() { 38 if(iter<list.size()) 39 return true; 40 else return false; 41 } 42 private: 43 vector<int> list; 44 int iter; 45 }; 46 47 /** 48 * Your NestedIterator object will be instantiated and called as such: 49 * NestedIterator i(nestedList); 50 * while (i.hasNext()) cout << i.next(); 51 */