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 Solution {
19: private:
20: int max_depth = 0;
21: public:
22: int depthSumInverse(vector<NestedInteger>& nestedList) {
23: depth(nestedList, 1);
24: return helper(nestedList, max_depth);
25: }
26: void depth(vector<NestedInteger> &nestedList, int d) {
27: max_depth = max(d, max_depth);
28: for (int i = 0; i < nestedList.size(); i++) {
29: if (!nestedList[i].isInteger()) depth(nestedList[i].getList(), d+1);
30: }
31: }
32: int helper(vector<NestedInteger> &nestedList, int d) {
33: int sum = 0;
34: for (int i = 0; i < nestedList.size(); i++) {
35: if (nestedList[i].isInteger()) sum += d * nestedList[i].getInteger();
36: else sum += helper(nestedList[i].getList(), d-1);
37: }
38: return sum;
39: }
40: };
Thursday, August 11, 2016
364. Nested List Weight Sum II
I made a mistake in first place where I was trying to get the maximum level for each nested list. This will get sum -2 for case [[-1], [[-1]]], which is wrong. We actually only need to get the maximum level once and pass the maximum level decreasingly down along the nested list.
Labels:
array,
DFS,
leetcode,
linkedin,
nested list
Subscribe to:
Post Comments (Atom)
We're Lucky to have a website like this for sarkari results as I am preparing for the government jobs exams in India. Thanks a million for maintaining the unique and rare content which is also helping me prepare for the exams.
ReplyDelete