Skip to content

339. Nested List Weight Sum #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tech-cow opened this issue Aug 5, 2019 · 0 comments
Closed

339. Nested List Weight Sum #59

tech-cow opened this issue Aug 5, 2019 · 0 comments

Comments

@tech-cow
Copy link
Owner

tech-cow commented Aug 5, 2019

第一遍

DFS

时空复杂: O(N) | O(depth)

知道Recursion
Can't Convert, DFS实现需要走一遍Python Tutor, Bottom-up 方法有点绕脑子。

class Solution(object):
    def depthSum(self, nestedList):
        return self.dfs(nestedList, 1)
    

    def dfs(self, nestedList, depth):
        res = 0
        for element in nestedList:
            if element.isInteger():
                res += element.getInteger() * depth
            else:
                res += self.dfs(element.getList(), depth + 1)
        return res

BFS

时空复杂: O(N) | O(N)

不知道initialize的时候enqueue什么,并且在expand的时候没有写for loop

from collections import deque
class Solution(object):
    def depthSum(self, nestedList):
        
        # 不知道enqueue什么。
        queue = deque([(1, element) for element in nestedList])
        res = 0
        
        while queue:
            depth, node = queue.popleft()
            
            if node.isInteger():
                res += node.getInteger() * depth
            else:
                # Enqueue这出错, 没写Tuple, 之后写成了depth,没写成depth + 1。然后没有写for loop。。。。。。。
                for children_node in node.getList():
                    queue.append((depth + 1, children_node))
            
        return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant