Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
optimal-account-balancing.py 986 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2019-02-19 22:54 +08:00 . Update optimal-account-balancing.py
# Time: O(n * 2^n), n is the size of the debt.
# Space: O(2^n)
import collections
class Solution(object):
def minTransfers(self, transactions):
"""
:type transactions: List[List[int]]
:rtype: int
"""
accounts = collections.defaultdict(int)
for transaction in transactions:
accounts[transaction[0]] += transaction[2]
accounts[transaction[1]] -= transaction[2]
debts = [account for account in accounts.values() if account]
dp = [0]*(2**len(debts))
sums = [0]*(2**len(debts))
for i in xrange(len(dp)):
for j in xrange(len(debts)):
if (i & (1<<j)) == 0:
nxt = i | (1<<j)
sums[nxt] = sums[i]+debts[j]
if sums[nxt] == 0:
dp[nxt] = max(dp[nxt], dp[i]+1)
else:
dp[nxt] = max(dp[nxt], dp[i])
return len(debts)-dp[-1]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助