1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int longestString(int x, int y, int z) { dp = new HashMap<>(); return dfs(x, y, z, ' '); }
Map<String, Integer> dp; private int dfs(int x, int y, int z, char lastChar) { if (x == 0 && y == 0 && z == 0) return 0; String key = x + "," + y + "," + z + "," + lastChar; if (dp.containsKey(key)) return dp.get(key); int max = 0; if (x > 0 && lastChar != 'A') max = Math.max(max, dfs(x - 1, y, z, 'A') + 2); if (y > 0 && lastChar != 'B') max = Math.max(max, dfs(x, y - 1, z, 'B') + 2); if (z > 0 && lastChar != 'A') max = Math.max(max, dfs(x, y, z - 1, 'B') + 2); dp.put(key, max); return max; } }
|