DFS to search all possible combine.
class Solution { public int minTransfers(int[][] transactions) { if (transactions.length == 0) return 0; int nums = 0; for (int[] trans : transactions) { nums = Math.max(nums, Math.max(trans[0], trans[1])); } int[] debt = new int[nums + 1]; for (int[] trans : transactions) { debt[trans[0]] += trans[2]; debt[trans[1]] -= trans[2]; } return dfs(debt, 0, 0); } private int dfs(int[] debt, int index, int count) { while (index < debt.length && debt[index] == 0) index++; int result = Integer.MAX_VALUE; for (int i = index + 1, prev = 0; i < debt.length; i++) { if (debt[i] != prev && debt[i] * debt[index] < 0) { debt[i] += debt[index]; result = Math.min(result, dfs(debt, index + 1, count + 1)); debt[i] -= debt[index]; prev = debt[i]; } } return result < Integer.MAX_VALUE ? result : count; } }