Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]] Output: 3 Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).
classSolution: defminReorder(self, n: int, connections: List[List[int]]) -> int: graph = defaultdict(list) # 构造无方向图 for s, d in connections: graph[s].append((d, 1)) # 这是s->d的原有路线,需要+1 graph[d].append((s, 0)) res = 0 queue = [0] visited = set([0]) while queue: node = queue.popleft() for n, cost in graph[node]: if n notin visted: visited.add(n) res += cost queue.append(n) return res
679. 24 Game
问题
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.
classSolution: defjudgePoint24(self, nums: List[int]) -> bool: iflen(nums)==1: returnround(nums[0], 4) == 24 for i inrange(len(nums)-1): for j inrange(i+1, len(nums)): first, second = nums[i], nums[j] left = nums[:i] + nums[i+1: j] + nums[j+1: ] if self.judgePoint24(left+[first+second]): returnTrue if self.judgePoint24(left+[first*second]): returnTrue if self.judgePoint24(left+[first-second]): returnTrue if self.judgePoint24(left+[second-first]): returnTrue if second and self.judgePoint24(left+[first/second]): returnTrue if first and self.judgePoint24(left+[second/first]): returnTrue returnFalse
tags: LeetcodeDFS
282. Expression Add Operators
问题
Given a string num that contains only digits and an integer target, return all possibilities to add the binary operators ‘+’, ‘-‘, or ‘*’ between the digits of num so that the resultant expression evaluates to the target value.
num = "" defdfs(l, r, expr, cur, last, res): # 结束条件 if l == r and cur == target: res.append(expr) return for i inrange(l+1, r+1): # why l+1? r+1? if i == l+1or (i > l+1and num[l] != "0"): # avoid start with 0 s, x = num[l:i], int(num[l:i]) # from l to i ! if last isNone: dfs(i, r, s, x, x, res) else: dfs(i, r, expr + "+" + s, cur+x, x, res) dfs(i, r, expr + "-" + s, cur-x, -x, res) dfs(i, r, expr + "*" + s, cur-last+last*x, res)