LeetCode 465. Optimal Account Balancing
原题链接在这里:https://leetcode.com/problems/optimal-account-balancing/
题目:
You are given an array of transactions transactions
where transactions[i] = [fromi, toi, amounti]
indicates that the person with ID = fromi
gave amounti $
to the person with ID = toi
.
Return the minimum number of transactions required to settle the debt.
Example 1:
Input: transactions = [[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: transactions = [[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.
Constraints:
1 <= transactions.length <= 8
transactions[i].length == 3
0 <= fromi, toi < 12
fromi != toi
1 <= amounti <= 100
题解:
For each transaction, it could create debt between two ppl.
We want to clear all ppl's debt.
We first get the debt for each person.
Any person's debt * debt[start] < 0 could help clear start's debt.
DFS state includes debt list, start person index.
Thinking 1 transaction cleared person start. Then the reset would be dfs(start + 1, debt).
Time Compexity: O(n!). T(n) = n * T(n - 1). n = transactions.length. On the first level, i is in the loop between [start, n]. On the second level, j is in the loop between [start + 1, n]. ... On the bottom level, k is in the loop between [n - 1, n].
Space: O(n).
AC Java:
1 class Solution { 2 public int minTransfers(int[][] transactions) { 3 HashMap<Integer, Integer> hm = new HashMap<>(); 4 for(int [] t : transactions){ 5 hm.put(t[0], hm.getOrDefault(t[0], 0) - t[2]); 6 hm.put(t[1], hm.getOrDefault(t[1], 0) + t[2]); 7 } 8 9 return dfs(0, new ArrayList<Integer>(hm.values())); 10 } 11 12 private int dfs(int start, ArrayList<Integer> debt){ 13 while(start < debt.size() && debt.get(start) == 0){ 14 start++; 15 } 16 17 if(start == debt.size()){ 18 return 0; 19 } 20 21 int res = Integer.MAX_VALUE; 22 for(int i = start + 1; i < debt.size(); i++){ 23 if(debt.get(start) * debt.get(i) < 0){ 24 debt.set(i, debt.get(i) + debt.get(start)); 25 res = Math.min(res, 1 + dfs(start + 1, debt)); 26 debt.set(i, debt.get(i) - debt.get(start)); 27 } 28 } 29 30 return res; 31 } 32 }