1、面试题 08.14. 布尔运算

考点:

1、DFS

class Solution:
    def countEval(self, s: str, result: int) -> int:
        self.ops = {
            '&': {
                True: [(True, True)],
                False: [(True, False), (False, True), (False, False)]
            },
            '|': {
                True: [(True, False), (False, True), (True, True)],
                False: [(False, False)]
            },
            '^': {
                True: [(True, False), (False, True)],
                False: [(True, True), (False, False)]
            }
        }

        return self.dfs(s, result, {})

    def dfs(self, s, target, memy):
        if (s, target) in memy:
            return memy[(s, target)]

        if len(s) == 1:
            return 1 if int(s) == target else 0

        all_count = 0
        for i in range(len(s)):
            if s[i] in self.ops:
                for ll,rr in self.ops[s[i]][target]:
                    all_count += self.dfs(s[:i], ll, memy) * self.dfs(s[i+1:], rr, memy)
        memy[(s, target)] = all_count
        return all_count

2、735. 行星碰撞

1、DFS

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:


        def dfs(asteroids):
            for i in range(len(asteroids) -1):
                # 相撞
                if asteroids[i] > 0 and asteroids[i+1] < 0:
                    print(asteroids[i])
                    if abs(asteroids[i]) > abs(asteroids[i+1]):
                        new_asteroids = list(asteroids)
                        del new_asteroids[i+1]
                        # print(new_asteroids)
                        return dfs(new_asteroids)
                    elif abs(asteroids[i]) == abs(asteroids[i+1]):
                        new_asteroids = list(asteroids)
                        del new_asteroids[i+1]
                        del new_asteroids[i]
                        # print(new_asteroids)
                        return dfs(new_asteroids)
                    else:
                        new_asteroids = list(asteroids)
                        del new_asteroids[i]
                        # print(new_asteroids)
                        return dfs(new_asteroids)
            return asteroids

        return dfs(asteroids)

  

 

posted @ 2020-12-09 20:15  哈哈哈喽喽喽  阅读(58)  评论(0编辑  收藏  举报