A group of friends went on holiday and sometimes lent each other money. For example, Alice paid for Bill's lunch for $10. Then later Chris gave Alice $5 for a taxi ride. We can model each transaction as a tuple (x, y, z) which means person x gave person y $z. Assuming Alice, Bill, and Chris are person 0, 1, and 2 respectively (0, 1, 2 are the person's ID), the transactions can be represented as [[0, 1, 10], [2, 0, 5]]
.
Given a list of transactions between a group of people, return the minimum number of transactions required to settle the debt.
Note:
- A transaction will be given as a tuple (x, y, z). Note that
x ≠ y
andz > 0
. - Person's IDs may not be linear, e.g. we could have the persons 0, 1, 2 or we could also have the persons 0, 2, 6.
Example 1:
Input: [[0,1,10], [2,0,5]] Output: 2 Explanation: Person #0 gave person #1 $10. Person #2 gave person #0 $5. Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
Example 2:
Input: [[0,1,10], [1,0,1], [1,2,5], [2,0,5]] Output: 1 Explanation: Person #0 gave person #1 $10. Person #1 gave person #0 $1. Person #1 gave person #2 $5. Person #2 gave person #0 $5. Therefore, person #1 only need to give person #0 $4, and all debt is settled.
這道題給了一堆某人欠某人多少錢這樣的賬單,問經過優化后最少還剩幾個。其實就相當於一堆人出去玩,某些人可能幫另一些人墊付過花費,最后結算總花費的時候可能你欠着別人的錢,其他人可能也欠你的欠,需要找出簡單的方法把所有欠賬都還清就行了。這道題的思路跟之前那道 Evaluate Division 有些像,都需要對一組數據顛倒順序處理。這里使用一個 HashMap 來建立每個人和其賬戶的映射,其中賬戶若為正數,說明其他人欠你錢;如果賬戶為負數,說明你欠別人錢。對於每份賬單,前面的人就在 HashMap 中減去錢數,后面的人在哈希表中加上錢數。這樣每個人就都有一個賬戶了,接下來要做的就是合並賬戶,看最少需要多少次匯款。先統計出賬戶值不為0的人數,因為如果為0了,表明你既不欠別人錢,別人也不欠你錢,如果不為0,把錢數放入一個數組 accnt 中,然后調用遞歸函數。在遞歸函數中,首先跳過為0的賬戶,然后看若此時 start 已經是 accnt 數組的長度了,說明所有的賬戶已經檢測完了,用 cnt 來更新結果 res。否則就開始遍歷之后的賬戶,如果當前賬戶和之前賬戶的錢數正負不同的話,將前一個賬戶的錢數加到當前賬戶上,這很好理解,比如前一個賬戶錢數是 -5,表示張三欠了別人5塊錢,當前賬戶錢數是5,表示某人欠了李四5塊錢,那么張三給李四5塊,這兩人的賬戶就都清零了。然后調用遞歸函數,此時從當前改變過的賬戶開始找,cnt 表示當前的轉賬數,需要加1,后面別忘了復原當前賬戶的值,典型的遞歸寫法,參見代碼如下:
class Solution { public: int minTransfers(vector<vector<int>>& transactions) { int res = INT_MAX; unordered_map<int, int> m; for (auto t : transactions) { m[t[0]] -= t[2]; m[t[1]] += t[2]; } vector<int> accnt; for (auto a : m) { if (a.second != 0) accnt.push_back(a.second); } helper(accnt, 0, 0, res); return res; } void helper(vector<int>& accnt, int start, int cnt, int& res) { int n = accnt.size(); while (start < n && accnt[start] == 0) ++start; if (start == n) { res = min(res, cnt); return; } for (int i = start + 1; i < n; ++i) { if ((accnt[i] < 0 && accnt[start] > 0) || (accnt[i] > 0 && accnt[start] < 0)) { accnt[i] += accnt[start]; helper(accnt, start + 1, cnt + 1, res); accnt[i] -= accnt[start]; } } } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/465
類似題目:
參考資料:
https://leetcode.com/problems/optimal-account-balancing/