1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public int connectTwoGroups(List<List<Integer>> cost) { int m = cost.size(), n = cost.get(0).size();
int[][] dp = new int[m + 1][1 << n]; for (int i = 0; i < dp.length; i++) { Arrays.fill(dp[i], Integer.MAX_VALUE / 2); } dp[0][0] = 0;
for (int i = 1; i <= m; i++) { for (int mask = 1; mask < dp[i].length; mask++) { for (int j = 0; j < n; j++) { if ((mask & (1 << j)) == 0) { continue; }
dp[i][mask] = Math.min(dp[i][mask], dp[i - 1][mask] + cost.get(i - 1).get(j)); dp[i][mask] = Math.min(dp[i][mask], dp[i][mask ^ (1 << j)] + cost.get(i - 1).get(j)); dp[i][mask] = Math.min(dp[i][mask], dp[i - 1][mask ^ (1 << j)] + cost.get(i - 1).get(j)); } } }
return dp[m][(1 << n) - 1]; } }
|
References
1595. Minimum Cost to Connect Two Groups of Points