339. Nested List Weight Sum - cocoder39/coco39_LC GitHub Wiki
implementation of the class
class NestedInteger:
def __init__(self, value=None):
self._is_integer = value is not None
if self._is_integer:
self._integer = value
self._list = None
else:
self._integer = None
self._list = []
def isInteger(self):
return self._is_integer
def getInteger(self):
return self._integer if self._is_integer else None
def setInteger(self, value):
self._is_integer = True
self._integer = value
self._list = None
def add(self, ni):
if not self._is_integer:
self._list.append(ni)
else:
self._is_integer = False
self._list = [NestedInteger(self._integer), ni]
self._integer = None
def getList(self):
return self._list if not self._is_integer else None
DFS search
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
return helper(nestedList, 1);
}
private:
int helper(vector<NestedInteger>& nestedList, int depth) {
int sum = 0;
for (auto list : nestedList) {
if (list.isInteger())
sum += depth * list.getInteger();
else
sum += helper(list.getList(), depth + 1);
}
return sum;
}
};