[Leetcode] 465. Optimal Account Balancing 解题报告

题目

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:

  1. A transaction will be given as a tuple (x, y, z). Note that x ≠ y and z > 0.
  2. 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.

思路

对于给定的所有交易,最终每个ID = id的人将具有一个总体负债bal[id]。我们注意到所有负债为0的人将与最终的结果无关,所以可以用一个更精炼的负债表debt[]来表示所有负债不为零的用户的负债信息,其中:

debt[i] > 0 表示该人需要向其他人支付debt[i]的金钱;

debt[i] < 0 表示该人需要接受来自其他人总计debt[i]的金钱。

我们从第一个负债debt[0]开始,看看所有它后面的人的负债信息,当搜索到第一个和debt负债信息sign相反的人i的信息时,我们就试图平衡这两个人之间的负债关系(即在0和i之间产生一个交易,使得debt[0]为0)。从此以后,用户0就负债清零了,所以我们再递归地查找后面的负债清零状况。在DFS的过程中,我们可以维护一个最小的交易次数,并最终返回。注意到在下面的代码片段中,我们用debt来记录上一次的交易数额,这样可以避免重复检测。另外需要注意到在循环的过程中,我们还需要做回溯。

我还有一个思路,就是将所有交易建模成为一个有向图,然后不断消边(假设A给B钱value1,而B给C钱value2,我们可以建立让A直接给C min(value1, value2)这样一条边,然后将A到B以及B到C之间的交易数额都减少min(value1, value2))直到最终无边可消。这样最终出边的数目之和(也就是入边的数目之和)就是最小的交易次数。不过代码没有通过大数据测试,说明效率还是过低。

代码

class Solution {
public:
    int minTransfers(vector>& transactions) {
        unordered_map bal;   // each person's overall balance
        for(auto &t: transactions) {
            bal[t[0]] -= t[2];
            bal[t[1]] += t[2];
        }
        for(auto &p: bal) {
            if(p.second) {
                debt.push_back(p.second);
            }
        }
        return dfs(0, 0);
    }
private:
    int dfs(int s, int cnt) {                       // min number of transactions to settle starting from debt[s]
    	while (s < debt.size() && !debt[s]) {
            ++s;                                    // get next non-zero debt
        }
    	int res = INT_MAX;
    	for (long i = s + 1, prev = 0; i < debt.size(); ++i) {
            if (debt[i] != prev && debt[i] * debt[s] < 0) {     // skip already tested or same sign debt
                debt[i] += debt[s];
                res = min(res, dfs(s + 1,cnt + 1));             // backtracking
                debt[i] -= debt[s];
                prev = debt[i];
            }
        }
    	return res < INT_MAX? res : cnt;
    }
    vector debt;                              // all non-zero balances
};

你可能感兴趣的:(IT公司面试习题)