[LeetCode]1601. Maximum Number of Achievable Transfer Requests (Hard) Python3-2023.07.02
Posted on 2023-07-03 02:10 Uriel 閱讀(51) 評論(0) 編輯 收藏 引用 所屬分類: 搜索 、閑來無事重切Leet Code一共有n個樓,給出一些requests,requestsi=[fromi, toi],代表一個人要求從from到to樓,問最多可以滿足多少個requests,使得最后每棟樓進出的人數一樣
直接DFS爆搜
直接DFS爆搜
1 #1601
2 #Runtime: 1254 ms (Beats 62.13%)
3 #Memory: 16.6 MB (Beats 33.98%)
4
5 class Solution:
6 def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
7 ans = 0
8 remain = [0] * n
9
10 def DFS(x, cnt):
11 nonlocal ans
12 if x == len(requests):
13 for i in range(n):
14 if remain[i]:
15 return
16 ans = max(ans, cnt)
17 return
18 remain[requests[x][0]] -= 1
19 remain[requests[x][1]] += 1
20 DFS(x + 1, cnt + 1)
21 remain[requests[x][0]] += 1
22 remain[requests[x][1]] -= 1
23 DFS(x + 1, cnt)
24
25 DFS(0, 0)
26 return ans
2 #Runtime: 1254 ms (Beats 62.13%)
3 #Memory: 16.6 MB (Beats 33.98%)
4
5 class Solution:
6 def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
7 ans = 0
8 remain = [0] * n
9
10 def DFS(x, cnt):
11 nonlocal ans
12 if x == len(requests):
13 for i in range(n):
14 if remain[i]:
15 return
16 ans = max(ans, cnt)
17 return
18 remain[requests[x][0]] -= 1
19 remain[requests[x][1]] += 1
20 DFS(x + 1, cnt + 1)
21 remain[requests[x][0]] += 1
22 remain[requests[x][1]] -= 1
23 DFS(x + 1, cnt)
24
25 DFS(0, 0)
26 return ans