https://discuss.leetcode.com/topic/76158/11-liner-9ms-dfs-solution-detailed-explanation
Solution:
思路:
Time Complexity: O(N!) Space Complexity: O(N)
Solution Code:
class Solution {
public int minTransfers(int[][] transactions) {
Map<Integer, Long> map = new HashMap();
// build id -> debt
for(int[] t: transactions){
long val1 = map.getOrDefault(t[0], 0L);
long val2 = map.getOrDefault(t[1], 0L);
map.put(t[0], val1 - t[2]);
map.put(t[1], val2 + t[2]);
}
// ignore those who dont has debt
List<Long> list = new ArrayList();
for(long val: map.values()) {
if(val != 0) list.add(val);
}
// list -> array, just for faster calc & convenient
Long[] debts = new Long[list.size()];
debts = list.toArray(debts);
// to counteract 抵消
return helper(debts, 0 , 0);
}
// dfs(backtracking)
int helper(Long[] debts, int pos, int count) {
while(pos < debts.length && debts[pos] == 0) pos++;
int res = Integer.MAX_VALUE;
long pre = 0;
for(int i = pos + 1; i < debts.length; i++) {
// look for other debts with opposite sign to debt[pos]
// pre: avoid same debt
if(debts[i] != pre && debts[i] * debts[pos] < 0) {
debts[i] += debts[pos];
res = Math.min(res, helper(debts, pos + 1, count + 1)); // enter recursive: debts[pos] has been taken care of
debts[i] = debts[i] - debts[pos]; // backtrack
pre = debts[i];
}
}
return res == Integer.MAX_VALUE ? count : res;
}
}