Approach
Depth-first search
For Maximum Product of the Length of Two Palindromic Subsequences, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 39 lines of Java from the credited upstream file 2002.java.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maxProduct(String s) {3 dfs(s, 0, new StringBuilder(), new StringBuilder());4 return ans;5 }6 7 private int ans = 0;8 9 private void dfs(final String s, int i, StringBuilder sb1, StringBuilder sb2) {10 if (i == s.length()) {11 if (isPalindrome(sb1) && isPalindrome(sb2))12 ans = Math.max(ans, sb1.length() * sb2.length());13 return;14 }15 16 final int sb1Length = sb1.length();17 dfs(s, i + 1, sb1.append(s.charAt(i)), sb2);18 sb1.setLength(sb1Length);19 20 final int sb2Length = sb2.length();21 dfs(s, i + 1, sb1, sb2.append(s.charAt(i)));22 sb2.setLength(sb2Length);23 24 dfs(s, i + 1, sb1, sb2);25 }26 27 private boolean isPalindrome(StringBuilder sb) {28 int i = 0;29 int j = sb.length() - 1;30 while (i < j) {31 if (sb.charAt(i) != sb.charAt(j))32 return false;33 ++i;34 --j;35 }36 return true;37 }38}39