My dp O(n^2) solution


  • 0
    A
    public static List<List<String>> partition(String s) {
        int n = s.length();
        char[] word = s.toCharArray();
        boolean[][] dp = new boolean[n][n];
        List<List<String>>[] ans = new List[n + 1];
        ans[0] = new LinkedList<>();
        ans[0].add(new LinkedList<String>());
        int j;
        String tmp;
        List<String> buf;
        for (int i = 0; i < n; i++) {
            ans[i + 1] = new LinkedList<>();
            for (j = 0; j <= i; j++) {
                dp[j][i] = i == j || word[i] == word[j] && (j == i - 1 || dp[j + 1][i - 1]);
                if (dp[j][i]) {
                    tmp = s.substring(j, i + 1);
                    for (List<String> l : ans[j]) {
                        buf = new LinkedList<>(l);
                        buf.add(tmp);
                        ans[i + 1].add(buf);
                    }
                }
            }
        }
        return ans[n];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.