package leetcode;

/**
 * https://leetcode.com/problems/palindrome-partitioning-ii/
 */
public class Problem132 {
    public int minCut(String s) {
        return minCut(s, 0, 1, s.length());
    }

    private static int minCut(String s, int i, int j, int max) {
        if (i == s.length() || j == s.length()) {
            return max;
        }
        String sub = s.substring(i, j);
        int min = max;
        if (isPalindrome(sub)) {
            min = Math.min(min, minCut(s, j, j + 1, max) - 1);
        }
        min = Math.min(min, minCut(s, i, j + 1, max));
        return min;
    }

    private static boolean isPalindrome(String s) {
        for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Problem132 prob = new Problem132();
        System.out.println(prob.minCut("aab")); // 1
        System.out.println(prob.minCut("aaa")); // 0
        System.out.println(prob.minCut("bbaaaaabb")); // 0
        System.out.println(prob.minCut("baaaaabb")); // 1
    }
}

@@ -133,32 +133,104 @@
 Cut(String s) %7B%0A
+        Integer%5B%5D%5B%5D memo = new Integer%5Bs.length() + 1%5D%5Bs.length() + 1%5D;%0A
         return m
@@ -244,26 +244,20 @@
 , 0, 1, 
-s.length()
+memo
 );%0A    %7D
@@ -316,15 +316,24 @@
  j, 
-int max
+Integer%5B%5D%5B%5D memo
 ) %7B%0A
@@ -365,18 +365,17 @@
 () %7C%7C j 
-==
+%3E
  s.lengt
@@ -400,19 +400,108 @@
  return 
-max
+Integer.MAX_VALUE;%0A        %7D%0A        if (memo%5Bi%5D%5Bj%5D != null) %7B%0A            return memo%5Bi%5D%5Bj%5D
 ;%0A      
@@ -562,19 +562,33 @@
 t min = 
-max
+Integer.MAX_VALUE
 ;%0A      
@@ -626,35 +626,25 @@
         
-m
 in
- = Math.min(min,
+t val =
  minCut(
@@ -661,17 +661,163 @@
 1, m
-ax) - 1);
+emo);%0A            if (val == Integer.MAX_VALUE) %7B%0A                min = 0;%0A            %7D else %7B%0A                min = Math.min(min, val + 1);%0A            %7D
 %0A   
@@ -876,12 +876,39 @@
 1, m
-ax))
+emo));%0A        memo%5Bi%5D%5Bj%5D = min
 ;%0A  
@@ -1264,16 +1264,124 @@
 m132();%0A
+        System.out.println(prob.minCut(%22abc%22)); // 2%0A        System.out.println(prob.minCut(%22abcde%22)); // 4%0A
         

Update problem 132