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 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public int minOperations(String s1, String s2, int x) { n = s1.length(); int cnt1 = 0, cnt2 = 0; for (int i = 0; i < n; ++i) { if (s1.charAt(i) == '1') ++cnt1; if (s2.charAt(i) == '1') ++cnt2; } if (cnt1 % 2 != cnt2 % 2) return -1; this.s1 = s1; this.s2 = s2; this.x = x; dp = new int[n][n + 1][2]; for (int[][] a : dp) for (int[] b : a) Arrays.fill(b, -1); return dfs(0, 0, false); }
public int dfs(int index, int key, boolean reverse) { if (index >= n) return key == 0 && !reverse ? 0 : inf; if (dp[index][key][reverse ? 1 : 0] != -1) return dp[index][key][reverse ? 1 : 0]; char ch1 = s1.charAt(index), ch2 = s2.charAt(index); if ((ch1 == ch2) == !reverse) return dp[index][key][reverse ? 1 : 0] = dfs(index + 1, key, false); int res = Math.min(dfs(index + 1, key + 1, false) + x, dfs(index + 1, key, true) + 1); if (key > 0) res = Math.min(res, dfs(index + 1, key - 1, false)); return dp[index][key][reverse ? 1 : 0] = res; }
String s1, s2; int x, inf = Integer.MAX_VALUE >> 1, n; int[][][] dp; }
|